]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - kernel/sched/core.c
UBUNTU: Start new release
[mirror_ubuntu-bionic-kernel.git] / kernel / sched / core.c
CommitLineData
1da177e4 1/*
391e43da 2 * kernel/sched/core.c
1da177e4 3 *
d1ccc66d 4 * Core kernel scheduler code and related syscalls
1da177e4
LT
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
1da177e4 7 */
004172bd 8#include <linux/sched.h>
e6017571 9#include <linux/sched/clock.h>
ae7e81c0 10#include <uapi/linux/sched/types.h>
4f17722c 11#include <linux/sched/loadavg.h>
ef8bd77f 12#include <linux/sched/hotplug.h>
5822a454 13#include <linux/wait_bit.h>
1da177e4 14#include <linux/cpuset.h>
0ff92245 15#include <linux/delayacct.h>
f1c6f1a7 16#include <linux/init_task.h>
91d1aa43 17#include <linux/context_tracking.h>
f9411ebe 18#include <linux/rcupdate_wait.h>
abca5fc5 19#include <linux/compat.h>
004172bd
IM
20
21#include <linux/blkdev.h>
22#include <linux/kprobes.h>
23#include <linux/mmu_context.h>
24#include <linux/module.h>
25#include <linux/nmi.h>
189485aa 26#include <linux/nospec.h>
6075620b 27#include <linux/prefetch.h>
004172bd
IM
28#include <linux/profile.h>
29#include <linux/security.h>
30#include <linux/syscalls.h>
78634061 31#include <linux/sched/isolation.h>
1da177e4 32
605478e2
PZ
33#include <linux/kthread.h>
34
96f951ed 35#include <asm/switch_to.h>
5517d86b 36#include <asm/tlb.h>
fd4a61e0
MB
37#ifdef CONFIG_PARAVIRT
38#include <asm/paravirt.h>
39#endif
1da177e4 40
029632fb 41#include "sched.h"
ea138446 42#include "../workqueue_internal.h"
29d5e047 43#include "../smpboot.h"
6e0534f2 44
a8d154b0 45#define CREATE_TRACE_POINTS
ad8d75ff 46#include <trace/events/sched.h>
a8d154b0 47
029632fb 48DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
dc61b1d6 49
765cc3a4 50#if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL)
bf5c91ba
IM
51/*
52 * Debugging: various feature bits
765cc3a4
PB
53 *
54 * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
55 * sysctl_sched_features, defined in sched.h, to allow constants propagation
56 * at compile time and compiler optimization based on features default.
bf5c91ba 57 */
f00b45c1
PZ
58#define SCHED_FEAT(name, enabled) \
59 (1UL << __SCHED_FEAT_##name) * enabled |
bf5c91ba 60const_debug unsigned int sysctl_sched_features =
391e43da 61#include "features.h"
f00b45c1 62 0;
f00b45c1 63#undef SCHED_FEAT
765cc3a4 64#endif
f00b45c1 65
b82d9fdd
PZ
66/*
67 * Number of tasks to iterate in a single balance run.
68 * Limited because this is done with IRQs disabled.
69 */
70const_debug unsigned int sysctl_sched_nr_migrate = 32;
71
e9e9250b
PZ
72/*
73 * period over which we average the RT time consumption, measured
74 * in ms.
75 *
76 * default: 1s
77 */
78const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
79
fa85ae24 80/*
d1ccc66d 81 * period over which we measure -rt task CPU usage in us.
fa85ae24
PZ
82 * default: 1s
83 */
9f0c1e56 84unsigned int sysctl_sched_rt_period = 1000000;
fa85ae24 85
029632fb 86__read_mostly int scheduler_running;
6892b75e 87
9f0c1e56
PZ
88/*
89 * part of the period that we allow rt tasks to run in us.
90 * default: 0.95s
91 */
92int sysctl_sched_rt_runtime = 950000;
fa85ae24 93
3e71a462
PZ
94/*
95 * __task_rq_lock - lock the rq @p resides on.
96 */
eb580751 97struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
98 __acquires(rq->lock)
99{
100 struct rq *rq;
101
102 lockdep_assert_held(&p->pi_lock);
103
104 for (;;) {
105 rq = task_rq(p);
106 raw_spin_lock(&rq->lock);
107 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 108 rq_pin_lock(rq, rf);
3e71a462
PZ
109 return rq;
110 }
111 raw_spin_unlock(&rq->lock);
112
113 while (unlikely(task_on_rq_migrating(p)))
114 cpu_relax();
115 }
116}
117
118/*
119 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
120 */
eb580751 121struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
3e71a462
PZ
122 __acquires(p->pi_lock)
123 __acquires(rq->lock)
124{
125 struct rq *rq;
126
127 for (;;) {
eb580751 128 raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
3e71a462
PZ
129 rq = task_rq(p);
130 raw_spin_lock(&rq->lock);
131 /*
132 * move_queued_task() task_rq_lock()
133 *
134 * ACQUIRE (rq->lock)
135 * [S] ->on_rq = MIGRATING [L] rq = task_rq()
136 * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
137 * [S] ->cpu = new_cpu [L] task_rq()
138 * [L] ->on_rq
139 * RELEASE (rq->lock)
140 *
141 * If we observe the old cpu in task_rq_lock, the acquire of
142 * the old rq->lock will fully serialize against the stores.
143 *
d1ccc66d 144 * If we observe the new CPU in task_rq_lock, the acquire will
3e71a462
PZ
145 * pair with the WMB to ensure we must then also see migrating.
146 */
147 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
d8ac8971 148 rq_pin_lock(rq, rf);
3e71a462
PZ
149 return rq;
150 }
151 raw_spin_unlock(&rq->lock);
eb580751 152 raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
3e71a462
PZ
153
154 while (unlikely(task_on_rq_migrating(p)))
155 cpu_relax();
156 }
157}
158
535b9552
IM
159/*
160 * RQ-clock updating methods:
161 */
162
163static void update_rq_clock_task(struct rq *rq, s64 delta)
164{
165/*
166 * In theory, the compile should just see 0 here, and optimize out the call
167 * to sched_rt_avg_update. But I don't trust it...
168 */
169#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
170 s64 steal = 0, irq_delta = 0;
171#endif
172#ifdef CONFIG_IRQ_TIME_ACCOUNTING
173 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
174
175 /*
176 * Since irq_time is only updated on {soft,}irq_exit, we might run into
177 * this case when a previous update_rq_clock() happened inside a
178 * {soft,}irq region.
179 *
180 * When this happens, we stop ->clock_task and only update the
181 * prev_irq_time stamp to account for the part that fit, so that a next
182 * update will consume the rest. This ensures ->clock_task is
183 * monotonic.
184 *
185 * It does however cause some slight miss-attribution of {soft,}irq
186 * time, a more accurate solution would be to update the irq_time using
187 * the current rq->clock timestamp, except that would require using
188 * atomic ops.
189 */
190 if (irq_delta > delta)
191 irq_delta = delta;
192
193 rq->prev_irq_time += irq_delta;
194 delta -= irq_delta;
195#endif
196#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
197 if (static_key_false((&paravirt_steal_rq_enabled))) {
198 steal = paravirt_steal_clock(cpu_of(rq));
199 steal -= rq->prev_steal_time_rq;
200
201 if (unlikely(steal > delta))
202 steal = delta;
203
204 rq->prev_steal_time_rq += steal;
205 delta -= steal;
206 }
207#endif
208
209 rq->clock_task += delta;
210
211#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
212 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
213 sched_rt_avg_update(rq, irq_delta + steal);
214#endif
215}
216
217void update_rq_clock(struct rq *rq)
218{
219 s64 delta;
220
221 lockdep_assert_held(&rq->lock);
222
223 if (rq->clock_update_flags & RQCF_ACT_SKIP)
224 return;
225
226#ifdef CONFIG_SCHED_DEBUG
26ae58d2
PZ
227 if (sched_feat(WARN_DOUBLE_CLOCK))
228 SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
535b9552
IM
229 rq->clock_update_flags |= RQCF_UPDATED;
230#endif
26ae58d2 231
535b9552
IM
232 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
233 if (delta < 0)
234 return;
235 rq->clock += delta;
236 update_rq_clock_task(rq, delta);
237}
238
239
8f4d37ec
PZ
240#ifdef CONFIG_SCHED_HRTICK
241/*
242 * Use HR-timers to deliver accurate preemption points.
8f4d37ec 243 */
8f4d37ec 244
8f4d37ec
PZ
245static void hrtick_clear(struct rq *rq)
246{
247 if (hrtimer_active(&rq->hrtick_timer))
248 hrtimer_cancel(&rq->hrtick_timer);
249}
250
8f4d37ec
PZ
251/*
252 * High-resolution timer tick.
253 * Runs from hardirq context with interrupts disabled.
254 */
255static enum hrtimer_restart hrtick(struct hrtimer *timer)
256{
257 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
8a8c69c3 258 struct rq_flags rf;
8f4d37ec
PZ
259
260 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
261
8a8c69c3 262 rq_lock(rq, &rf);
3e51f33f 263 update_rq_clock(rq);
8f4d37ec 264 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
8a8c69c3 265 rq_unlock(rq, &rf);
8f4d37ec
PZ
266
267 return HRTIMER_NORESTART;
268}
269
95e904c7 270#ifdef CONFIG_SMP
971ee28c 271
4961b6e1 272static void __hrtick_restart(struct rq *rq)
971ee28c
PZ
273{
274 struct hrtimer *timer = &rq->hrtick_timer;
971ee28c 275
4961b6e1 276 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
971ee28c
PZ
277}
278
31656519
PZ
279/*
280 * called from hardirq (IPI) context
281 */
282static void __hrtick_start(void *arg)
b328ca18 283{
31656519 284 struct rq *rq = arg;
8a8c69c3 285 struct rq_flags rf;
b328ca18 286
8a8c69c3 287 rq_lock(rq, &rf);
971ee28c 288 __hrtick_restart(rq);
31656519 289 rq->hrtick_csd_pending = 0;
8a8c69c3 290 rq_unlock(rq, &rf);
b328ca18
PZ
291}
292
31656519
PZ
293/*
294 * Called to set the hrtick timer state.
295 *
296 * called with rq->lock held and irqs disabled
297 */
029632fb 298void hrtick_start(struct rq *rq, u64 delay)
b328ca18 299{
31656519 300 struct hrtimer *timer = &rq->hrtick_timer;
177ef2a6 301 ktime_t time;
302 s64 delta;
303
304 /*
305 * Don't schedule slices shorter than 10000ns, that just
306 * doesn't make sense and can cause timer DoS.
307 */
308 delta = max_t(s64, delay, 10000LL);
309 time = ktime_add_ns(timer->base->get_time(), delta);
b328ca18 310
cc584b21 311 hrtimer_set_expires(timer, time);
31656519
PZ
312
313 if (rq == this_rq()) {
971ee28c 314 __hrtick_restart(rq);
31656519 315 } else if (!rq->hrtick_csd_pending) {
c46fff2a 316 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
31656519
PZ
317 rq->hrtick_csd_pending = 1;
318 }
b328ca18
PZ
319}
320
31656519
PZ
321#else
322/*
323 * Called to set the hrtick timer state.
324 *
325 * called with rq->lock held and irqs disabled
326 */
029632fb 327void hrtick_start(struct rq *rq, u64 delay)
31656519 328{
86893335
WL
329 /*
330 * Don't schedule slices shorter than 10000ns, that just
331 * doesn't make sense. Rely on vruntime for fairness.
332 */
333 delay = max_t(u64, delay, 10000LL);
4961b6e1
TG
334 hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
335 HRTIMER_MODE_REL_PINNED);
31656519 336}
31656519 337#endif /* CONFIG_SMP */
8f4d37ec 338
31656519 339static void init_rq_hrtick(struct rq *rq)
8f4d37ec 340{
31656519
PZ
341#ifdef CONFIG_SMP
342 rq->hrtick_csd_pending = 0;
8f4d37ec 343
31656519
PZ
344 rq->hrtick_csd.flags = 0;
345 rq->hrtick_csd.func = __hrtick_start;
346 rq->hrtick_csd.info = rq;
347#endif
8f4d37ec 348
31656519
PZ
349 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
350 rq->hrtick_timer.function = hrtick;
8f4d37ec 351}
006c75f1 352#else /* CONFIG_SCHED_HRTICK */
8f4d37ec
PZ
353static inline void hrtick_clear(struct rq *rq)
354{
355}
356
8f4d37ec
PZ
357static inline void init_rq_hrtick(struct rq *rq)
358{
359}
006c75f1 360#endif /* CONFIG_SCHED_HRTICK */
8f4d37ec 361
5529578a
FW
362/*
363 * cmpxchg based fetch_or, macro so it works for different integer types
364 */
365#define fetch_or(ptr, mask) \
366 ({ \
367 typeof(ptr) _ptr = (ptr); \
368 typeof(mask) _mask = (mask); \
369 typeof(*_ptr) _old, _val = *_ptr; \
370 \
371 for (;;) { \
372 _old = cmpxchg(_ptr, _val, _val | _mask); \
373 if (_old == _val) \
374 break; \
375 _val = _old; \
376 } \
377 _old; \
378})
379
e3baac47 380#if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
fd99f91a
PZ
381/*
382 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
383 * this avoids any races wrt polling state changes and thereby avoids
384 * spurious IPIs.
385 */
386static bool set_nr_and_not_polling(struct task_struct *p)
387{
388 struct thread_info *ti = task_thread_info(p);
389 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
390}
e3baac47
PZ
391
392/*
393 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
394 *
395 * If this returns true, then the idle task promises to call
396 * sched_ttwu_pending() and reschedule soon.
397 */
398static bool set_nr_if_polling(struct task_struct *p)
399{
400 struct thread_info *ti = task_thread_info(p);
316c1608 401 typeof(ti->flags) old, val = READ_ONCE(ti->flags);
e3baac47
PZ
402
403 for (;;) {
404 if (!(val & _TIF_POLLING_NRFLAG))
405 return false;
406 if (val & _TIF_NEED_RESCHED)
407 return true;
408 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
409 if (old == val)
410 break;
411 val = old;
412 }
413 return true;
414}
415
fd99f91a
PZ
416#else
417static bool set_nr_and_not_polling(struct task_struct *p)
418{
419 set_tsk_need_resched(p);
420 return true;
421}
e3baac47
PZ
422
423#ifdef CONFIG_SMP
424static bool set_nr_if_polling(struct task_struct *p)
425{
426 return false;
427}
428#endif
fd99f91a
PZ
429#endif
430
76751049
PZ
431void wake_q_add(struct wake_q_head *head, struct task_struct *task)
432{
433 struct wake_q_node *node = &task->wake_q;
434
435 /*
436 * Atomically grab the task, if ->wake_q is !nil already it means
437 * its already queued (either by us or someone else) and will get the
438 * wakeup due to that.
439 *
440 * This cmpxchg() implies a full barrier, which pairs with the write
58fe9c46 441 * barrier implied by the wakeup in wake_up_q().
76751049
PZ
442 */
443 if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
444 return;
445
446 get_task_struct(task);
447
448 /*
449 * The head is context local, there can be no concurrency.
450 */
451 *head->lastp = node;
452 head->lastp = &node->next;
453}
454
455void wake_up_q(struct wake_q_head *head)
456{
457 struct wake_q_node *node = head->first;
458
459 while (node != WAKE_Q_TAIL) {
460 struct task_struct *task;
461
462 task = container_of(node, struct task_struct, wake_q);
463 BUG_ON(!task);
d1ccc66d 464 /* Task can safely be re-inserted now: */
76751049
PZ
465 node = node->next;
466 task->wake_q.next = NULL;
467
468 /*
469 * wake_up_process() implies a wmb() to pair with the queueing
470 * in wake_q_add() so as not to miss wakeups.
471 */
472 wake_up_process(task);
473 put_task_struct(task);
474 }
475}
476
c24d20db 477/*
8875125e 478 * resched_curr - mark rq's current task 'to be rescheduled now'.
c24d20db
IM
479 *
480 * On UP this means the setting of the need_resched flag, on SMP it
481 * might also involve a cross-CPU call to trigger the scheduler on
482 * the target CPU.
483 */
8875125e 484void resched_curr(struct rq *rq)
c24d20db 485{
8875125e 486 struct task_struct *curr = rq->curr;
c24d20db
IM
487 int cpu;
488
8875125e 489 lockdep_assert_held(&rq->lock);
c24d20db 490
8875125e 491 if (test_tsk_need_resched(curr))
c24d20db
IM
492 return;
493
8875125e 494 cpu = cpu_of(rq);
fd99f91a 495
f27dde8d 496 if (cpu == smp_processor_id()) {
8875125e 497 set_tsk_need_resched(curr);
f27dde8d 498 set_preempt_need_resched();
c24d20db 499 return;
f27dde8d 500 }
c24d20db 501
8875125e 502 if (set_nr_and_not_polling(curr))
c24d20db 503 smp_send_reschedule(cpu);
dfc68f29
AL
504 else
505 trace_sched_wake_idle_without_ipi(cpu);
c24d20db
IM
506}
507
029632fb 508void resched_cpu(int cpu)
c24d20db
IM
509{
510 struct rq *rq = cpu_rq(cpu);
511 unsigned long flags;
512
7c2102e5 513 raw_spin_lock_irqsave(&rq->lock, flags);
971c873f
PM
514 if (cpu_online(cpu) || cpu == smp_processor_id())
515 resched_curr(rq);
05fa785c 516 raw_spin_unlock_irqrestore(&rq->lock, flags);
c24d20db 517}
06d8308c 518
b021fe3e 519#ifdef CONFIG_SMP
3451d024 520#ifdef CONFIG_NO_HZ_COMMON
83cd4fe2 521/*
d1ccc66d
IM
522 * In the semi idle case, use the nearest busy CPU for migrating timers
523 * from an idle CPU. This is good for power-savings.
83cd4fe2
VP
524 *
525 * We don't do similar optimization for completely idle system, as
d1ccc66d
IM
526 * selecting an idle CPU will add more delays to the timers than intended
527 * (as that CPU's timer base may not be uptodate wrt jiffies etc).
83cd4fe2 528 */
bc7a34b8 529int get_nohz_timer_target(void)
83cd4fe2 530{
bc7a34b8 531 int i, cpu = smp_processor_id();
83cd4fe2
VP
532 struct sched_domain *sd;
533
de201559 534 if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
6201b4d6
VK
535 return cpu;
536
057f3fad 537 rcu_read_lock();
83cd4fe2 538 for_each_domain(cpu, sd) {
057f3fad 539 for_each_cpu(i, sched_domain_span(sd)) {
44496922
WL
540 if (cpu == i)
541 continue;
542
de201559 543 if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
057f3fad
PZ
544 cpu = i;
545 goto unlock;
546 }
547 }
83cd4fe2 548 }
9642d18e 549
de201559
FW
550 if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
551 cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
057f3fad
PZ
552unlock:
553 rcu_read_unlock();
83cd4fe2
VP
554 return cpu;
555}
d1ccc66d 556
06d8308c
TG
557/*
558 * When add_timer_on() enqueues a timer into the timer wheel of an
559 * idle CPU then this timer might expire before the next timer event
560 * which is scheduled to wake up that CPU. In case of a completely
561 * idle system the next event might even be infinite time into the
562 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
563 * leaves the inner idle loop so the newly added timer is taken into
564 * account when the CPU goes back to idle and evaluates the timer
565 * wheel for the next timer event.
566 */
1c20091e 567static void wake_up_idle_cpu(int cpu)
06d8308c
TG
568{
569 struct rq *rq = cpu_rq(cpu);
570
571 if (cpu == smp_processor_id())
572 return;
573
67b9ca70 574 if (set_nr_and_not_polling(rq->idle))
06d8308c 575 smp_send_reschedule(cpu);
dfc68f29
AL
576 else
577 trace_sched_wake_idle_without_ipi(cpu);
45bf76df
IM
578}
579
c5bfece2 580static bool wake_up_full_nohz_cpu(int cpu)
1c20091e 581{
53c5fa16
FW
582 /*
583 * We just need the target to call irq_exit() and re-evaluate
584 * the next tick. The nohz full kick at least implies that.
585 * If needed we can still optimize that later with an
586 * empty IRQ.
587 */
379d9ecb
PM
588 if (cpu_is_offline(cpu))
589 return true; /* Don't try to wake offline CPUs. */
c5bfece2 590 if (tick_nohz_full_cpu(cpu)) {
1c20091e
FW
591 if (cpu != smp_processor_id() ||
592 tick_nohz_tick_stopped())
53c5fa16 593 tick_nohz_full_kick_cpu(cpu);
1c20091e
FW
594 return true;
595 }
596
597 return false;
598}
599
379d9ecb
PM
600/*
601 * Wake up the specified CPU. If the CPU is going offline, it is the
602 * caller's responsibility to deal with the lost wakeup, for example,
603 * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
604 */
1c20091e
FW
605void wake_up_nohz_cpu(int cpu)
606{
c5bfece2 607 if (!wake_up_full_nohz_cpu(cpu))
1c20091e
FW
608 wake_up_idle_cpu(cpu);
609}
610
ca38062e 611static inline bool got_nohz_idle_kick(void)
45bf76df 612{
1c792db7 613 int cpu = smp_processor_id();
873b4c65
VG
614
615 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
616 return false;
617
618 if (idle_cpu(cpu) && !need_resched())
619 return true;
620
621 /*
622 * We can't run Idle Load Balance on this CPU for this time so we
623 * cancel it and clear NOHZ_BALANCE_KICK
624 */
625 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
626 return false;
45bf76df
IM
627}
628
3451d024 629#else /* CONFIG_NO_HZ_COMMON */
45bf76df 630
ca38062e 631static inline bool got_nohz_idle_kick(void)
2069dd75 632{
ca38062e 633 return false;
2069dd75
PZ
634}
635
3451d024 636#endif /* CONFIG_NO_HZ_COMMON */
d842de87 637
ce831b38 638#ifdef CONFIG_NO_HZ_FULL
76d92ac3 639bool sched_can_stop_tick(struct rq *rq)
ce831b38 640{
76d92ac3
FW
641 int fifo_nr_running;
642
643 /* Deadline tasks, even if single, need the tick */
644 if (rq->dl.dl_nr_running)
645 return false;
646
1e78cdbd 647 /*
2548d546
PZ
648 * If there are more than one RR tasks, we need the tick to effect the
649 * actual RR behaviour.
1e78cdbd 650 */
76d92ac3
FW
651 if (rq->rt.rr_nr_running) {
652 if (rq->rt.rr_nr_running == 1)
653 return true;
654 else
655 return false;
1e78cdbd
RR
656 }
657
2548d546
PZ
658 /*
659 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
660 * forced preemption between FIFO tasks.
661 */
662 fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
663 if (fifo_nr_running)
664 return true;
665
666 /*
667 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
668 * if there's more than one we need the tick for involuntary
669 * preemption.
670 */
671 if (rq->nr_running > 1)
541b8264 672 return false;
ce831b38 673
541b8264 674 return true;
ce831b38
FW
675}
676#endif /* CONFIG_NO_HZ_FULL */
d842de87 677
029632fb 678void sched_avg_update(struct rq *rq)
18d95a28 679{
e9e9250b
PZ
680 s64 period = sched_avg_period();
681
78becc27 682 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
0d98bb26
WD
683 /*
684 * Inline assembly required to prevent the compiler
685 * optimising this loop into a divmod call.
686 * See __iter_div_u64_rem() for another example of this.
687 */
688 asm("" : "+rm" (rq->age_stamp));
e9e9250b
PZ
689 rq->age_stamp += period;
690 rq->rt_avg /= 2;
691 }
18d95a28
PZ
692}
693
6d6bc0ad 694#endif /* CONFIG_SMP */
18d95a28 695
a790de99
PT
696#if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
697 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
c09595f6 698/*
8277434e
PT
699 * Iterate task_group tree rooted at *from, calling @down when first entering a
700 * node and @up when leaving it for the final time.
701 *
702 * Caller must hold rcu_lock or sufficient equivalent.
c09595f6 703 */
029632fb 704int walk_tg_tree_from(struct task_group *from,
8277434e 705 tg_visitor down, tg_visitor up, void *data)
c09595f6
PZ
706{
707 struct task_group *parent, *child;
eb755805 708 int ret;
c09595f6 709
8277434e
PT
710 parent = from;
711
c09595f6 712down:
eb755805
PZ
713 ret = (*down)(parent, data);
714 if (ret)
8277434e 715 goto out;
c09595f6
PZ
716 list_for_each_entry_rcu(child, &parent->children, siblings) {
717 parent = child;
718 goto down;
719
720up:
721 continue;
722 }
eb755805 723 ret = (*up)(parent, data);
8277434e
PT
724 if (ret || parent == from)
725 goto out;
c09595f6
PZ
726
727 child = parent;
728 parent = parent->parent;
729 if (parent)
730 goto up;
8277434e 731out:
eb755805 732 return ret;
c09595f6
PZ
733}
734
029632fb 735int tg_nop(struct task_group *tg, void *data)
eb755805 736{
e2b245f8 737 return 0;
eb755805 738}
18d95a28
PZ
739#endif
740
9059393e 741static void set_load_weight(struct task_struct *p, bool update_load)
45bf76df 742{
f05998d4
NR
743 int prio = p->static_prio - MAX_RT_PRIO;
744 struct load_weight *load = &p->se.load;
745
dd41f596
IM
746 /*
747 * SCHED_IDLE tasks get minimal weight:
748 */
20f9cd2a 749 if (idle_policy(p->policy)) {
c8b28116 750 load->weight = scale_load(WEIGHT_IDLEPRIO);
f05998d4 751 load->inv_weight = WMULT_IDLEPRIO;
dd41f596
IM
752 return;
753 }
71f8bd46 754
9059393e
VG
755 /*
756 * SCHED_OTHER tasks have to update their load when changing their
757 * weight
758 */
759 if (update_load && p->sched_class == &fair_sched_class) {
760 reweight_task(p, prio);
761 } else {
762 load->weight = scale_load(sched_prio_to_weight[prio]);
763 load->inv_weight = sched_prio_to_wmult[prio];
764 }
71f8bd46
IM
765}
766
1de64443 767static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
2087a1ad 768{
0a67d1ee
PZ
769 if (!(flags & ENQUEUE_NOCLOCK))
770 update_rq_clock(rq);
771
1de64443
PZ
772 if (!(flags & ENQUEUE_RESTORE))
773 sched_info_queued(rq, p);
0a67d1ee 774
371fd7e7 775 p->sched_class->enqueue_task(rq, p, flags);
71f8bd46
IM
776}
777
1de64443 778static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
71f8bd46 779{
0a67d1ee
PZ
780 if (!(flags & DEQUEUE_NOCLOCK))
781 update_rq_clock(rq);
782
1de64443
PZ
783 if (!(flags & DEQUEUE_SAVE))
784 sched_info_dequeued(rq, p);
0a67d1ee 785
371fd7e7 786 p->sched_class->dequeue_task(rq, p, flags);
71f8bd46
IM
787}
788
029632fb 789void activate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
790{
791 if (task_contributes_to_load(p))
792 rq->nr_uninterruptible--;
793
371fd7e7 794 enqueue_task(rq, p, flags);
1e3c88bd
PZ
795}
796
029632fb 797void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1e3c88bd
PZ
798{
799 if (task_contributes_to_load(p))
800 rq->nr_uninterruptible++;
801
371fd7e7 802 dequeue_task(rq, p, flags);
1e3c88bd
PZ
803}
804
14531189 805/*
dd41f596 806 * __normal_prio - return the priority that is based on the static prio
14531189 807 */
14531189
IM
808static inline int __normal_prio(struct task_struct *p)
809{
dd41f596 810 return p->static_prio;
14531189
IM
811}
812
b29739f9
IM
813/*
814 * Calculate the expected normal priority: i.e. priority
815 * without taking RT-inheritance into account. Might be
816 * boosted by interactivity modifiers. Changes upon fork,
817 * setprio syscalls, and whenever the interactivity
818 * estimator recalculates.
819 */
36c8b586 820static inline int normal_prio(struct task_struct *p)
b29739f9
IM
821{
822 int prio;
823
aab03e05
DF
824 if (task_has_dl_policy(p))
825 prio = MAX_DL_PRIO-1;
826 else if (task_has_rt_policy(p))
b29739f9
IM
827 prio = MAX_RT_PRIO-1 - p->rt_priority;
828 else
829 prio = __normal_prio(p);
830 return prio;
831}
832
833/*
834 * Calculate the current priority, i.e. the priority
835 * taken into account by the scheduler. This value might
836 * be boosted by RT tasks, or might be boosted by
837 * interactivity modifiers. Will be RT if the task got
838 * RT-boosted. If not then it returns p->normal_prio.
839 */
36c8b586 840static int effective_prio(struct task_struct *p)
b29739f9
IM
841{
842 p->normal_prio = normal_prio(p);
843 /*
844 * If we are RT tasks or we were boosted to RT priority,
845 * keep the priority unchanged. Otherwise, update priority
846 * to the normal priority:
847 */
848 if (!rt_prio(p->prio))
849 return p->normal_prio;
850 return p->prio;
851}
852
1da177e4
LT
853/**
854 * task_curr - is this task currently executing on a CPU?
855 * @p: the task in question.
e69f6186
YB
856 *
857 * Return: 1 if the task is currently executing. 0 otherwise.
1da177e4 858 */
36c8b586 859inline int task_curr(const struct task_struct *p)
1da177e4
LT
860{
861 return cpu_curr(task_cpu(p)) == p;
862}
863
67dfa1b7 864/*
4c9a4bc8
PZ
865 * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
866 * use the balance_callback list if you want balancing.
867 *
868 * this means any call to check_class_changed() must be followed by a call to
869 * balance_callback().
67dfa1b7 870 */
cb469845
SR
871static inline void check_class_changed(struct rq *rq, struct task_struct *p,
872 const struct sched_class *prev_class,
da7a735e 873 int oldprio)
cb469845
SR
874{
875 if (prev_class != p->sched_class) {
876 if (prev_class->switched_from)
da7a735e 877 prev_class->switched_from(rq, p);
4c9a4bc8 878
da7a735e 879 p->sched_class->switched_to(rq, p);
2d3d891d 880 } else if (oldprio != p->prio || dl_task(p))
da7a735e 881 p->sched_class->prio_changed(rq, p, oldprio);
cb469845
SR
882}
883
029632fb 884void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1e5a7405
PZ
885{
886 const struct sched_class *class;
887
888 if (p->sched_class == rq->curr->sched_class) {
889 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
890 } else {
891 for_each_class(class) {
892 if (class == rq->curr->sched_class)
893 break;
894 if (class == p->sched_class) {
8875125e 895 resched_curr(rq);
1e5a7405
PZ
896 break;
897 }
898 }
899 }
900
901 /*
902 * A queue event has occurred, and we're going to schedule. In
903 * this case, we can save a useless back to back clock update.
904 */
da0c1e65 905 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
9edfbfed 906 rq_clock_skip_update(rq, true);
1e5a7405
PZ
907}
908
1da177e4 909#ifdef CONFIG_SMP
5cc389bc
PZ
910/*
911 * This is how migration works:
912 *
913 * 1) we invoke migration_cpu_stop() on the target CPU using
914 * stop_one_cpu().
915 * 2) stopper starts to run (implicitly forcing the migrated thread
916 * off the CPU)
917 * 3) it checks whether the migrated task is still in the wrong runqueue.
918 * 4) if it's in the wrong runqueue then the migration thread removes
919 * it and puts it into the right queue.
920 * 5) stopper completes and stop_one_cpu() returns and the migration
921 * is done.
922 */
923
924/*
925 * move_queued_task - move a queued task to new rq.
926 *
927 * Returns (locked) new rq. Old rq's lock is released.
928 */
8a8c69c3
PZ
929static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
930 struct task_struct *p, int new_cpu)
5cc389bc 931{
5cc389bc
PZ
932 lockdep_assert_held(&rq->lock);
933
5cc389bc 934 p->on_rq = TASK_ON_RQ_MIGRATING;
15ff991e 935 dequeue_task(rq, p, DEQUEUE_NOCLOCK);
5cc389bc 936 set_task_cpu(p, new_cpu);
8a8c69c3 937 rq_unlock(rq, rf);
5cc389bc
PZ
938
939 rq = cpu_rq(new_cpu);
940
8a8c69c3 941 rq_lock(rq, rf);
5cc389bc 942 BUG_ON(task_cpu(p) != new_cpu);
5cc389bc 943 enqueue_task(rq, p, 0);
3ea94de1 944 p->on_rq = TASK_ON_RQ_QUEUED;
5cc389bc
PZ
945 check_preempt_curr(rq, p, 0);
946
947 return rq;
948}
949
950struct migration_arg {
951 struct task_struct *task;
952 int dest_cpu;
953};
954
955/*
d1ccc66d 956 * Move (not current) task off this CPU, onto the destination CPU. We're doing
5cc389bc
PZ
957 * this because either it can't run here any more (set_cpus_allowed()
958 * away from this CPU, or CPU going down), or because we're
959 * attempting to rebalance this task on exec (sched_exec).
960 *
961 * So we race with normal scheduler movements, but that's OK, as long
962 * as the task is no longer on this CPU.
5cc389bc 963 */
8a8c69c3
PZ
964static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
965 struct task_struct *p, int dest_cpu)
5cc389bc 966{
955dbdf4
TH
967 if (p->flags & PF_KTHREAD) {
968 if (unlikely(!cpu_online(dest_cpu)))
969 return rq;
970 } else {
971 if (unlikely(!cpu_active(dest_cpu)))
972 return rq;
973 }
5cc389bc
PZ
974
975 /* Affinity changed (again). */
0c98d344 976 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
5e16bbc2 977 return rq;
5cc389bc 978
15ff991e 979 update_rq_clock(rq);
8a8c69c3 980 rq = move_queued_task(rq, rf, p, dest_cpu);
5e16bbc2
PZ
981
982 return rq;
5cc389bc
PZ
983}
984
985/*
986 * migration_cpu_stop - this will be executed by a highprio stopper thread
987 * and performs thread migration by bumping thread off CPU then
988 * 'pushing' onto another runqueue.
989 */
990static int migration_cpu_stop(void *data)
991{
992 struct migration_arg *arg = data;
5e16bbc2
PZ
993 struct task_struct *p = arg->task;
994 struct rq *rq = this_rq();
8a8c69c3 995 struct rq_flags rf;
5cc389bc
PZ
996
997 /*
d1ccc66d
IM
998 * The original target CPU might have gone down and we might
999 * be on another CPU but it doesn't matter.
5cc389bc
PZ
1000 */
1001 local_irq_disable();
1002 /*
1003 * We need to explicitly wake pending tasks before running
1004 * __migrate_task() such that we will not miss enforcing cpus_allowed
1005 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1006 */
1007 sched_ttwu_pending();
5e16bbc2
PZ
1008
1009 raw_spin_lock(&p->pi_lock);
8a8c69c3 1010 rq_lock(rq, &rf);
5e16bbc2
PZ
1011 /*
1012 * If task_rq(p) != rq, it cannot be migrated here, because we're
1013 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1014 * we're holding p->pi_lock.
1015 */
bf89a304
CC
1016 if (task_rq(p) == rq) {
1017 if (task_on_rq_queued(p))
8a8c69c3 1018 rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
bf89a304
CC
1019 else
1020 p->wake_cpu = arg->dest_cpu;
1021 }
8a8c69c3 1022 rq_unlock(rq, &rf);
5e16bbc2
PZ
1023 raw_spin_unlock(&p->pi_lock);
1024
5cc389bc
PZ
1025 local_irq_enable();
1026 return 0;
1027}
1028
c5b28038
PZ
1029/*
1030 * sched_class::set_cpus_allowed must do the below, but is not required to
1031 * actually call this function.
1032 */
1033void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
5cc389bc 1034{
5cc389bc
PZ
1035 cpumask_copy(&p->cpus_allowed, new_mask);
1036 p->nr_cpus_allowed = cpumask_weight(new_mask);
1037}
1038
c5b28038
PZ
1039void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1040{
6c37067e
PZ
1041 struct rq *rq = task_rq(p);
1042 bool queued, running;
1043
c5b28038 1044 lockdep_assert_held(&p->pi_lock);
6c37067e
PZ
1045
1046 queued = task_on_rq_queued(p);
1047 running = task_current(rq, p);
1048
1049 if (queued) {
1050 /*
1051 * Because __kthread_bind() calls this on blocked tasks without
1052 * holding rq->lock.
1053 */
1054 lockdep_assert_held(&rq->lock);
7a57f32a 1055 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
6c37067e
PZ
1056 }
1057 if (running)
1058 put_prev_task(rq, p);
1059
c5b28038 1060 p->sched_class->set_cpus_allowed(p, new_mask);
6c37067e 1061
6c37067e 1062 if (queued)
7134b3e9 1063 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 1064 if (running)
b2bf6c31 1065 set_curr_task(rq, p);
c5b28038
PZ
1066}
1067
5cc389bc
PZ
1068/*
1069 * Change a given task's CPU affinity. Migrate the thread to a
1070 * proper CPU and schedule it away if the CPU it's executing on
1071 * is removed from the allowed bitmask.
1072 *
1073 * NOTE: the caller must have a valid reference to the task, the
1074 * task must not exit() & deallocate itself prematurely. The
1075 * call is not atomic; no spinlocks may be held.
1076 */
25834c73
PZ
1077static int __set_cpus_allowed_ptr(struct task_struct *p,
1078 const struct cpumask *new_mask, bool check)
5cc389bc 1079{
e9d867a6 1080 const struct cpumask *cpu_valid_mask = cpu_active_mask;
5cc389bc 1081 unsigned int dest_cpu;
eb580751
PZ
1082 struct rq_flags rf;
1083 struct rq *rq;
5cc389bc
PZ
1084 int ret = 0;
1085
eb580751 1086 rq = task_rq_lock(p, &rf);
a499c3ea 1087 update_rq_clock(rq);
5cc389bc 1088
e9d867a6
PZI
1089 if (p->flags & PF_KTHREAD) {
1090 /*
1091 * Kernel threads are allowed on online && !active CPUs
1092 */
1093 cpu_valid_mask = cpu_online_mask;
1094 }
1095
25834c73
PZ
1096 /*
1097 * Must re-check here, to close a race against __kthread_bind(),
1098 * sched_setaffinity() is not guaranteed to observe the flag.
1099 */
1100 if (check && (p->flags & PF_NO_SETAFFINITY)) {
1101 ret = -EINVAL;
1102 goto out;
1103 }
1104
5cc389bc
PZ
1105 if (cpumask_equal(&p->cpus_allowed, new_mask))
1106 goto out;
1107
e9d867a6 1108 if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
5cc389bc
PZ
1109 ret = -EINVAL;
1110 goto out;
1111 }
1112
1113 do_set_cpus_allowed(p, new_mask);
1114
e9d867a6
PZI
1115 if (p->flags & PF_KTHREAD) {
1116 /*
1117 * For kernel threads that do indeed end up on online &&
d1ccc66d 1118 * !active we want to ensure they are strict per-CPU threads.
e9d867a6
PZI
1119 */
1120 WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1121 !cpumask_intersects(new_mask, cpu_active_mask) &&
1122 p->nr_cpus_allowed != 1);
1123 }
1124
5cc389bc
PZ
1125 /* Can the task run on the task's current CPU? If so, we're done */
1126 if (cpumask_test_cpu(task_cpu(p), new_mask))
1127 goto out;
1128
e9d867a6 1129 dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
5cc389bc
PZ
1130 if (task_running(rq, p) || p->state == TASK_WAKING) {
1131 struct migration_arg arg = { p, dest_cpu };
1132 /* Need help from migration thread: drop lock and wait. */
eb580751 1133 task_rq_unlock(rq, p, &rf);
5cc389bc
PZ
1134 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1135 tlb_migrate_finish(p->mm);
1136 return 0;
cbce1a68
PZ
1137 } else if (task_on_rq_queued(p)) {
1138 /*
1139 * OK, since we're going to drop the lock immediately
1140 * afterwards anyway.
1141 */
8a8c69c3 1142 rq = move_queued_task(rq, &rf, p, dest_cpu);
cbce1a68 1143 }
5cc389bc 1144out:
eb580751 1145 task_rq_unlock(rq, p, &rf);
5cc389bc
PZ
1146
1147 return ret;
1148}
25834c73
PZ
1149
1150int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1151{
1152 return __set_cpus_allowed_ptr(p, new_mask, false);
1153}
5cc389bc
PZ
1154EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1155
dd41f596 1156void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 1157{
e2912009
PZ
1158#ifdef CONFIG_SCHED_DEBUG
1159 /*
1160 * We should never call set_task_cpu() on a blocked task,
1161 * ttwu() will sort out the placement.
1162 */
077614ee 1163 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
e2336f6e 1164 !p->on_rq);
0122ec5b 1165
3ea94de1
JP
1166 /*
1167 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1168 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1169 * time relying on p->on_rq.
1170 */
1171 WARN_ON_ONCE(p->state == TASK_RUNNING &&
1172 p->sched_class == &fair_sched_class &&
1173 (p->on_rq && !task_on_rq_migrating(p)));
1174
0122ec5b 1175#ifdef CONFIG_LOCKDEP
6c6c54e1
PZ
1176 /*
1177 * The caller should hold either p->pi_lock or rq->lock, when changing
1178 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1179 *
1180 * sched_move_task() holds both and thus holding either pins the cgroup,
8323f26c 1181 * see task_group().
6c6c54e1
PZ
1182 *
1183 * Furthermore, all task_rq users should acquire both locks, see
1184 * task_rq_lock().
1185 */
0122ec5b
PZ
1186 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1187 lockdep_is_held(&task_rq(p)->lock)));
1188#endif
4ff9083b
PZ
1189 /*
1190 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1191 */
1192 WARN_ON_ONCE(!cpu_online(new_cpu));
e2912009
PZ
1193#endif
1194
de1d7286 1195 trace_sched_migrate_task(p, new_cpu);
cbc34ed1 1196
0c69774e 1197 if (task_cpu(p) != new_cpu) {
0a74bef8 1198 if (p->sched_class->migrate_task_rq)
5a4fd036 1199 p->sched_class->migrate_task_rq(p);
0c69774e 1200 p->se.nr_migrations++;
ff303e66 1201 perf_event_task_migrate(p);
0c69774e 1202 }
dd41f596
IM
1203
1204 __set_task_cpu(p, new_cpu);
c65cc870
IM
1205}
1206
ac66f547
PZ
1207static void __migrate_swap_task(struct task_struct *p, int cpu)
1208{
da0c1e65 1209 if (task_on_rq_queued(p)) {
ac66f547 1210 struct rq *src_rq, *dst_rq;
8a8c69c3 1211 struct rq_flags srf, drf;
ac66f547
PZ
1212
1213 src_rq = task_rq(p);
1214 dst_rq = cpu_rq(cpu);
1215
8a8c69c3
PZ
1216 rq_pin_lock(src_rq, &srf);
1217 rq_pin_lock(dst_rq, &drf);
1218
3ea94de1 1219 p->on_rq = TASK_ON_RQ_MIGRATING;
ac66f547
PZ
1220 deactivate_task(src_rq, p, 0);
1221 set_task_cpu(p, cpu);
1222 activate_task(dst_rq, p, 0);
3ea94de1 1223 p->on_rq = TASK_ON_RQ_QUEUED;
ac66f547 1224 check_preempt_curr(dst_rq, p, 0);
8a8c69c3
PZ
1225
1226 rq_unpin_lock(dst_rq, &drf);
1227 rq_unpin_lock(src_rq, &srf);
1228
ac66f547
PZ
1229 } else {
1230 /*
1231 * Task isn't running anymore; make it appear like we migrated
1232 * it before it went to sleep. This means on wakeup we make the
d1ccc66d 1233 * previous CPU our target instead of where it really is.
ac66f547
PZ
1234 */
1235 p->wake_cpu = cpu;
1236 }
1237}
1238
1239struct migration_swap_arg {
1240 struct task_struct *src_task, *dst_task;
1241 int src_cpu, dst_cpu;
1242};
1243
1244static int migrate_swap_stop(void *data)
1245{
1246 struct migration_swap_arg *arg = data;
1247 struct rq *src_rq, *dst_rq;
1248 int ret = -EAGAIN;
1249
62694cd5
PZ
1250 if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1251 return -EAGAIN;
1252
ac66f547
PZ
1253 src_rq = cpu_rq(arg->src_cpu);
1254 dst_rq = cpu_rq(arg->dst_cpu);
1255
74602315
PZ
1256 double_raw_lock(&arg->src_task->pi_lock,
1257 &arg->dst_task->pi_lock);
ac66f547 1258 double_rq_lock(src_rq, dst_rq);
62694cd5 1259
ac66f547
PZ
1260 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1261 goto unlock;
1262
1263 if (task_cpu(arg->src_task) != arg->src_cpu)
1264 goto unlock;
1265
0c98d344 1266 if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
ac66f547
PZ
1267 goto unlock;
1268
0c98d344 1269 if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
ac66f547
PZ
1270 goto unlock;
1271
1272 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1273 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1274
1275 ret = 0;
1276
1277unlock:
1278 double_rq_unlock(src_rq, dst_rq);
74602315
PZ
1279 raw_spin_unlock(&arg->dst_task->pi_lock);
1280 raw_spin_unlock(&arg->src_task->pi_lock);
ac66f547
PZ
1281
1282 return ret;
1283}
1284
1285/*
1286 * Cross migrate two tasks
1287 */
1288int migrate_swap(struct task_struct *cur, struct task_struct *p)
1289{
1290 struct migration_swap_arg arg;
1291 int ret = -EINVAL;
1292
ac66f547
PZ
1293 arg = (struct migration_swap_arg){
1294 .src_task = cur,
1295 .src_cpu = task_cpu(cur),
1296 .dst_task = p,
1297 .dst_cpu = task_cpu(p),
1298 };
1299
1300 if (arg.src_cpu == arg.dst_cpu)
1301 goto out;
1302
6acce3ef
PZ
1303 /*
1304 * These three tests are all lockless; this is OK since all of them
1305 * will be re-checked with proper locks held further down the line.
1306 */
ac66f547
PZ
1307 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1308 goto out;
1309
0c98d344 1310 if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
ac66f547
PZ
1311 goto out;
1312
0c98d344 1313 if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
ac66f547
PZ
1314 goto out;
1315
286549dc 1316 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
ac66f547
PZ
1317 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1318
1319out:
ac66f547
PZ
1320 return ret;
1321}
1322
1da177e4
LT
1323/*
1324 * wait_task_inactive - wait for a thread to unschedule.
1325 *
85ba2d86
RM
1326 * If @match_state is nonzero, it's the @p->state value just checked and
1327 * not expected to change. If it changes, i.e. @p might have woken up,
1328 * then return zero. When we succeed in waiting for @p to be off its CPU,
1329 * we return a positive number (its total switch count). If a second call
1330 * a short while later returns the same number, the caller can be sure that
1331 * @p has remained unscheduled the whole time.
1332 *
1da177e4
LT
1333 * The caller must ensure that the task *will* unschedule sometime soon,
1334 * else this function might spin for a *long* time. This function can't
1335 * be called with interrupts off, or it may introduce deadlock with
1336 * smp_call_function() if an IPI is sent by the same process we are
1337 * waiting to become inactive.
1338 */
85ba2d86 1339unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1da177e4 1340{
da0c1e65 1341 int running, queued;
eb580751 1342 struct rq_flags rf;
85ba2d86 1343 unsigned long ncsw;
70b97a7f 1344 struct rq *rq;
1da177e4 1345
3a5c359a
AK
1346 for (;;) {
1347 /*
1348 * We do the initial early heuristics without holding
1349 * any task-queue locks at all. We'll only try to get
1350 * the runqueue lock when things look like they will
1351 * work out!
1352 */
1353 rq = task_rq(p);
fa490cfd 1354
3a5c359a
AK
1355 /*
1356 * If the task is actively running on another CPU
1357 * still, just relax and busy-wait without holding
1358 * any locks.
1359 *
1360 * NOTE! Since we don't hold any locks, it's not
1361 * even sure that "rq" stays as the right runqueue!
1362 * But we don't care, since "task_running()" will
1363 * return false if the runqueue has changed and p
1364 * is actually now running somewhere else!
1365 */
85ba2d86
RM
1366 while (task_running(rq, p)) {
1367 if (match_state && unlikely(p->state != match_state))
1368 return 0;
3a5c359a 1369 cpu_relax();
85ba2d86 1370 }
fa490cfd 1371
3a5c359a
AK
1372 /*
1373 * Ok, time to look more closely! We need the rq
1374 * lock now, to be *sure*. If we're wrong, we'll
1375 * just go back and repeat.
1376 */
eb580751 1377 rq = task_rq_lock(p, &rf);
27a9da65 1378 trace_sched_wait_task(p);
3a5c359a 1379 running = task_running(rq, p);
da0c1e65 1380 queued = task_on_rq_queued(p);
85ba2d86 1381 ncsw = 0;
f31e11d8 1382 if (!match_state || p->state == match_state)
93dcf55f 1383 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
eb580751 1384 task_rq_unlock(rq, p, &rf);
fa490cfd 1385
85ba2d86
RM
1386 /*
1387 * If it changed from the expected state, bail out now.
1388 */
1389 if (unlikely(!ncsw))
1390 break;
1391
3a5c359a
AK
1392 /*
1393 * Was it really running after all now that we
1394 * checked with the proper locks actually held?
1395 *
1396 * Oops. Go back and try again..
1397 */
1398 if (unlikely(running)) {
1399 cpu_relax();
1400 continue;
1401 }
fa490cfd 1402
3a5c359a
AK
1403 /*
1404 * It's not enough that it's not actively running,
1405 * it must be off the runqueue _entirely_, and not
1406 * preempted!
1407 *
80dd99b3 1408 * So if it was still runnable (but just not actively
3a5c359a
AK
1409 * running right now), it's preempted, and we should
1410 * yield - it could be a while.
1411 */
da0c1e65 1412 if (unlikely(queued)) {
8b0e1953 1413 ktime_t to = NSEC_PER_SEC / HZ;
8eb90c30
TG
1414
1415 set_current_state(TASK_UNINTERRUPTIBLE);
1416 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
3a5c359a
AK
1417 continue;
1418 }
fa490cfd 1419
3a5c359a
AK
1420 /*
1421 * Ahh, all good. It wasn't running, and it wasn't
1422 * runnable, which means that it will never become
1423 * running in the future either. We're all done!
1424 */
1425 break;
1426 }
85ba2d86
RM
1427
1428 return ncsw;
1da177e4
LT
1429}
1430
1431/***
1432 * kick_process - kick a running thread to enter/exit the kernel
1433 * @p: the to-be-kicked thread
1434 *
1435 * Cause a process which is running on another CPU to enter
1436 * kernel-mode, without any delay. (to get signals handled.)
1437 *
25985edc 1438 * NOTE: this function doesn't have to take the runqueue lock,
1da177e4
LT
1439 * because all it wants to ensure is that the remote task enters
1440 * the kernel. If the IPI races and the task has been migrated
1441 * to another CPU then no harm is done and the purpose has been
1442 * achieved as well.
1443 */
36c8b586 1444void kick_process(struct task_struct *p)
1da177e4
LT
1445{
1446 int cpu;
1447
1448 preempt_disable();
1449 cpu = task_cpu(p);
1450 if ((cpu != smp_processor_id()) && task_curr(p))
1451 smp_send_reschedule(cpu);
1452 preempt_enable();
1453}
b43e3521 1454EXPORT_SYMBOL_GPL(kick_process);
1da177e4 1455
30da688e 1456/*
013fdb80 1457 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
e9d867a6
PZI
1458 *
1459 * A few notes on cpu_active vs cpu_online:
1460 *
1461 * - cpu_active must be a subset of cpu_online
1462 *
1463 * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
1464 * see __set_cpus_allowed_ptr(). At this point the newly online
d1ccc66d 1465 * CPU isn't yet part of the sched domains, and balancing will not
e9d867a6
PZI
1466 * see it.
1467 *
d1ccc66d 1468 * - on CPU-down we clear cpu_active() to mask the sched domains and
e9d867a6 1469 * avoid the load balancer to place new tasks on the to be removed
d1ccc66d 1470 * CPU. Existing tasks will remain running there and will be taken
e9d867a6
PZI
1471 * off.
1472 *
1473 * This means that fallback selection must not select !active CPUs.
1474 * And can assume that any active CPU must be online. Conversely
1475 * select_task_rq() below may allow selection of !active CPUs in order
1476 * to satisfy the above rules.
30da688e 1477 */
5da9a0fb
PZ
1478static int select_fallback_rq(int cpu, struct task_struct *p)
1479{
aa00d89c
TC
1480 int nid = cpu_to_node(cpu);
1481 const struct cpumask *nodemask = NULL;
2baab4e9
PZ
1482 enum { cpuset, possible, fail } state = cpuset;
1483 int dest_cpu;
5da9a0fb 1484
aa00d89c 1485 /*
d1ccc66d
IM
1486 * If the node that the CPU is on has been offlined, cpu_to_node()
1487 * will return -1. There is no CPU on the node, and we should
1488 * select the CPU on the other node.
aa00d89c
TC
1489 */
1490 if (nid != -1) {
1491 nodemask = cpumask_of_node(nid);
1492
1493 /* Look for allowed, online CPU in same node. */
1494 for_each_cpu(dest_cpu, nodemask) {
aa00d89c
TC
1495 if (!cpu_active(dest_cpu))
1496 continue;
0c98d344 1497 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
aa00d89c
TC
1498 return dest_cpu;
1499 }
2baab4e9 1500 }
5da9a0fb 1501
2baab4e9
PZ
1502 for (;;) {
1503 /* Any allowed, online CPU? */
0c98d344 1504 for_each_cpu(dest_cpu, &p->cpus_allowed) {
feb245e3
TH
1505 if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
1506 continue;
1507 if (!cpu_online(dest_cpu))
2baab4e9
PZ
1508 continue;
1509 goto out;
1510 }
5da9a0fb 1511
e73e85f0 1512 /* No more Mr. Nice Guy. */
2baab4e9
PZ
1513 switch (state) {
1514 case cpuset:
e73e85f0
ON
1515 if (IS_ENABLED(CONFIG_CPUSETS)) {
1516 cpuset_cpus_allowed_fallback(p);
1517 state = possible;
1518 break;
1519 }
d1ccc66d 1520 /* Fall-through */
2baab4e9
PZ
1521 case possible:
1522 do_set_cpus_allowed(p, cpu_possible_mask);
1523 state = fail;
1524 break;
1525
1526 case fail:
1527 BUG();
1528 break;
1529 }
1530 }
1531
1532out:
1533 if (state != cpuset) {
1534 /*
1535 * Don't tell them about moving exiting tasks or
1536 * kernel threads (both mm NULL), since they never
1537 * leave kernel.
1538 */
1539 if (p->mm && printk_ratelimit()) {
aac74dc4 1540 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
2baab4e9
PZ
1541 task_pid_nr(p), p->comm, cpu);
1542 }
5da9a0fb
PZ
1543 }
1544
1545 return dest_cpu;
1546}
1547
e2912009 1548/*
013fdb80 1549 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
e2912009 1550 */
970b13ba 1551static inline
ac66f547 1552int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
970b13ba 1553{
cbce1a68
PZ
1554 lockdep_assert_held(&p->pi_lock);
1555
4b53a341 1556 if (p->nr_cpus_allowed > 1)
6c1d9410 1557 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
e9d867a6 1558 else
0c98d344 1559 cpu = cpumask_any(&p->cpus_allowed);
e2912009
PZ
1560
1561 /*
1562 * In order not to call set_task_cpu() on a blocking task we need
1563 * to rely on ttwu() to place the task on a valid ->cpus_allowed
d1ccc66d 1564 * CPU.
e2912009
PZ
1565 *
1566 * Since this is common to all placement strategies, this lives here.
1567 *
1568 * [ this allows ->select_task() to simply return task_cpu(p) and
1569 * not worry about this generic constraint ]
1570 */
0c98d344 1571 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
70f11205 1572 !cpu_online(cpu)))
5da9a0fb 1573 cpu = select_fallback_rq(task_cpu(p), p);
e2912009
PZ
1574
1575 return cpu;
970b13ba 1576}
09a40af5
MG
1577
1578static void update_avg(u64 *avg, u64 sample)
1579{
1580 s64 diff = sample - *avg;
1581 *avg += diff >> 3;
1582}
25834c73 1583
f5832c19
NP
1584void sched_set_stop_task(int cpu, struct task_struct *stop)
1585{
1586 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1587 struct task_struct *old_stop = cpu_rq(cpu)->stop;
1588
1589 if (stop) {
1590 /*
1591 * Make it appear like a SCHED_FIFO task, its something
1592 * userspace knows about and won't get confused about.
1593 *
1594 * Also, it will make PI more or less work without too
1595 * much confusion -- but then, stop work should not
1596 * rely on PI working anyway.
1597 */
1598 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
1599
1600 stop->sched_class = &stop_sched_class;
1601 }
1602
1603 cpu_rq(cpu)->stop = stop;
1604
1605 if (old_stop) {
1606 /*
1607 * Reset it back to a normal scheduling class so that
1608 * it can die in pieces.
1609 */
1610 old_stop->sched_class = &rt_sched_class;
1611 }
1612}
1613
25834c73
PZ
1614#else
1615
1616static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1617 const struct cpumask *new_mask, bool check)
1618{
1619 return set_cpus_allowed_ptr(p, new_mask);
1620}
1621
5cc389bc 1622#endif /* CONFIG_SMP */
970b13ba 1623
d7c01d27 1624static void
b84cb5df 1625ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
9ed3811a 1626{
4fa8d299 1627 struct rq *rq;
b84cb5df 1628
4fa8d299
JP
1629 if (!schedstat_enabled())
1630 return;
1631
1632 rq = this_rq();
d7c01d27 1633
4fa8d299
JP
1634#ifdef CONFIG_SMP
1635 if (cpu == rq->cpu) {
ae92882e
JP
1636 schedstat_inc(rq->ttwu_local);
1637 schedstat_inc(p->se.statistics.nr_wakeups_local);
d7c01d27
PZ
1638 } else {
1639 struct sched_domain *sd;
1640
ae92882e 1641 schedstat_inc(p->se.statistics.nr_wakeups_remote);
057f3fad 1642 rcu_read_lock();
4fa8d299 1643 for_each_domain(rq->cpu, sd) {
d7c01d27 1644 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
ae92882e 1645 schedstat_inc(sd->ttwu_wake_remote);
d7c01d27
PZ
1646 break;
1647 }
1648 }
057f3fad 1649 rcu_read_unlock();
d7c01d27 1650 }
f339b9dc
PZ
1651
1652 if (wake_flags & WF_MIGRATED)
ae92882e 1653 schedstat_inc(p->se.statistics.nr_wakeups_migrate);
d7c01d27
PZ
1654#endif /* CONFIG_SMP */
1655
ae92882e
JP
1656 schedstat_inc(rq->ttwu_count);
1657 schedstat_inc(p->se.statistics.nr_wakeups);
d7c01d27
PZ
1658
1659 if (wake_flags & WF_SYNC)
ae92882e 1660 schedstat_inc(p->se.statistics.nr_wakeups_sync);
d7c01d27
PZ
1661}
1662
1de64443 1663static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
d7c01d27 1664{
9ed3811a 1665 activate_task(rq, p, en_flags);
da0c1e65 1666 p->on_rq = TASK_ON_RQ_QUEUED;
c2f7115e 1667
d1ccc66d 1668 /* If a worker is waking up, notify the workqueue: */
c2f7115e
PZ
1669 if (p->flags & PF_WQ_WORKER)
1670 wq_worker_waking_up(p, cpu_of(rq));
9ed3811a
TH
1671}
1672
23f41eeb
PZ
1673/*
1674 * Mark the task runnable and perform wakeup-preemption.
1675 */
e7904a28 1676static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 1677 struct rq_flags *rf)
9ed3811a 1678{
9ed3811a 1679 check_preempt_curr(rq, p, wake_flags);
9ed3811a 1680 p->state = TASK_RUNNING;
fbd705a0
PZ
1681 trace_sched_wakeup(p);
1682
9ed3811a 1683#ifdef CONFIG_SMP
4c9a4bc8
PZ
1684 if (p->sched_class->task_woken) {
1685 /*
cbce1a68
PZ
1686 * Our task @p is fully woken up and running; so its safe to
1687 * drop the rq->lock, hereafter rq is only used for statistics.
4c9a4bc8 1688 */
d8ac8971 1689 rq_unpin_lock(rq, rf);
9ed3811a 1690 p->sched_class->task_woken(rq, p);
d8ac8971 1691 rq_repin_lock(rq, rf);
4c9a4bc8 1692 }
9ed3811a 1693
e69c6341 1694 if (rq->idle_stamp) {
78becc27 1695 u64 delta = rq_clock(rq) - rq->idle_stamp;
9bd721c5 1696 u64 max = 2*rq->max_idle_balance_cost;
9ed3811a 1697
abfafa54
JL
1698 update_avg(&rq->avg_idle, delta);
1699
1700 if (rq->avg_idle > max)
9ed3811a 1701 rq->avg_idle = max;
abfafa54 1702
9ed3811a
TH
1703 rq->idle_stamp = 0;
1704 }
1705#endif
1706}
1707
c05fbafb 1708static void
e7904a28 1709ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
d8ac8971 1710 struct rq_flags *rf)
c05fbafb 1711{
77558e4d 1712 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
b5179ac7 1713
cbce1a68
PZ
1714 lockdep_assert_held(&rq->lock);
1715
c05fbafb
PZ
1716#ifdef CONFIG_SMP
1717 if (p->sched_contributes_to_load)
1718 rq->nr_uninterruptible--;
b5179ac7 1719
b5179ac7 1720 if (wake_flags & WF_MIGRATED)
59efa0ba 1721 en_flags |= ENQUEUE_MIGRATED;
c05fbafb
PZ
1722#endif
1723
b5179ac7 1724 ttwu_activate(rq, p, en_flags);
d8ac8971 1725 ttwu_do_wakeup(rq, p, wake_flags, rf);
c05fbafb
PZ
1726}
1727
1728/*
1729 * Called in case the task @p isn't fully descheduled from its runqueue,
1730 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1731 * since all we need to do is flip p->state to TASK_RUNNING, since
1732 * the task is still ->on_rq.
1733 */
1734static int ttwu_remote(struct task_struct *p, int wake_flags)
1735{
eb580751 1736 struct rq_flags rf;
c05fbafb
PZ
1737 struct rq *rq;
1738 int ret = 0;
1739
eb580751 1740 rq = __task_rq_lock(p, &rf);
da0c1e65 1741 if (task_on_rq_queued(p)) {
1ad4ec0d
FW
1742 /* check_preempt_curr() may use rq clock */
1743 update_rq_clock(rq);
d8ac8971 1744 ttwu_do_wakeup(rq, p, wake_flags, &rf);
c05fbafb
PZ
1745 ret = 1;
1746 }
eb580751 1747 __task_rq_unlock(rq, &rf);
c05fbafb
PZ
1748
1749 return ret;
1750}
1751
317f3941 1752#ifdef CONFIG_SMP
e3baac47 1753void sched_ttwu_pending(void)
317f3941
PZ
1754{
1755 struct rq *rq = this_rq();
fa14ff4a 1756 struct llist_node *llist = llist_del_all(&rq->wake_list);
73215849 1757 struct task_struct *p, *t;
d8ac8971 1758 struct rq_flags rf;
317f3941 1759
e3baac47
PZ
1760 if (!llist)
1761 return;
1762
8a8c69c3 1763 rq_lock_irqsave(rq, &rf);
77558e4d 1764 update_rq_clock(rq);
317f3941 1765
73215849
BP
1766 llist_for_each_entry_safe(p, t, llist, wake_entry)
1767 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
317f3941 1768
8a8c69c3 1769 rq_unlock_irqrestore(rq, &rf);
317f3941
PZ
1770}
1771
1772void scheduler_ipi(void)
1773{
f27dde8d
PZ
1774 /*
1775 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1776 * TIF_NEED_RESCHED remotely (for the first time) will also send
1777 * this IPI.
1778 */
8cb75e0c 1779 preempt_fold_need_resched();
f27dde8d 1780
fd2ac4f4 1781 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
c5d753a5
PZ
1782 return;
1783
1784 /*
1785 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1786 * traditionally all their work was done from the interrupt return
1787 * path. Now that we actually do some work, we need to make sure
1788 * we do call them.
1789 *
1790 * Some archs already do call them, luckily irq_enter/exit nest
1791 * properly.
1792 *
1793 * Arguably we should visit all archs and update all handlers,
1794 * however a fair share of IPIs are still resched only so this would
1795 * somewhat pessimize the simple resched case.
1796 */
1797 irq_enter();
fa14ff4a 1798 sched_ttwu_pending();
ca38062e
SS
1799
1800 /*
1801 * Check if someone kicked us for doing the nohz idle load balance.
1802 */
873b4c65 1803 if (unlikely(got_nohz_idle_kick())) {
6eb57e0d 1804 this_rq()->idle_balance = 1;
ca38062e 1805 raise_softirq_irqoff(SCHED_SOFTIRQ);
6eb57e0d 1806 }
c5d753a5 1807 irq_exit();
317f3941
PZ
1808}
1809
b7e7ade3 1810static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
317f3941 1811{
e3baac47
PZ
1812 struct rq *rq = cpu_rq(cpu);
1813
b7e7ade3
PZ
1814 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1815
e3baac47
PZ
1816 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1817 if (!set_nr_if_polling(rq->idle))
1818 smp_send_reschedule(cpu);
1819 else
1820 trace_sched_wake_idle_without_ipi(cpu);
1821 }
317f3941 1822}
d6aa8f85 1823
f6be8af1
CL
1824void wake_up_if_idle(int cpu)
1825{
1826 struct rq *rq = cpu_rq(cpu);
8a8c69c3 1827 struct rq_flags rf;
f6be8af1 1828
fd7de1e8
AL
1829 rcu_read_lock();
1830
1831 if (!is_idle_task(rcu_dereference(rq->curr)))
1832 goto out;
f6be8af1
CL
1833
1834 if (set_nr_if_polling(rq->idle)) {
1835 trace_sched_wake_idle_without_ipi(cpu);
1836 } else {
8a8c69c3 1837 rq_lock_irqsave(rq, &rf);
f6be8af1
CL
1838 if (is_idle_task(rq->curr))
1839 smp_send_reschedule(cpu);
d1ccc66d 1840 /* Else CPU is not idle, do nothing here: */
8a8c69c3 1841 rq_unlock_irqrestore(rq, &rf);
f6be8af1 1842 }
fd7de1e8
AL
1843
1844out:
1845 rcu_read_unlock();
f6be8af1
CL
1846}
1847
39be3501 1848bool cpus_share_cache(int this_cpu, int that_cpu)
518cd623
PZ
1849{
1850 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1851}
d6aa8f85 1852#endif /* CONFIG_SMP */
317f3941 1853
b5179ac7 1854static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
c05fbafb
PZ
1855{
1856 struct rq *rq = cpu_rq(cpu);
d8ac8971 1857 struct rq_flags rf;
c05fbafb 1858
17d9f311 1859#if defined(CONFIG_SMP)
39be3501 1860 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
d1ccc66d 1861 sched_clock_cpu(cpu); /* Sync clocks across CPUs */
b7e7ade3 1862 ttwu_queue_remote(p, cpu, wake_flags);
317f3941
PZ
1863 return;
1864 }
1865#endif
1866
8a8c69c3 1867 rq_lock(rq, &rf);
77558e4d 1868 update_rq_clock(rq);
d8ac8971 1869 ttwu_do_activate(rq, p, wake_flags, &rf);
8a8c69c3 1870 rq_unlock(rq, &rf);
9ed3811a
TH
1871}
1872
8643cda5
PZ
1873/*
1874 * Notes on Program-Order guarantees on SMP systems.
1875 *
1876 * MIGRATION
1877 *
1878 * The basic program-order guarantee on SMP systems is that when a task [t]
d1ccc66d
IM
1879 * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1880 * execution on its new CPU [c1].
8643cda5
PZ
1881 *
1882 * For migration (of runnable tasks) this is provided by the following means:
1883 *
1884 * A) UNLOCK of the rq(c0)->lock scheduling out task t
1885 * B) migration for t is required to synchronize *both* rq(c0)->lock and
1886 * rq(c1)->lock (if not at the same time, then in that order).
1887 * C) LOCK of the rq(c1)->lock scheduling in task
1888 *
1889 * Transitivity guarantees that B happens after A and C after B.
1890 * Note: we only require RCpc transitivity.
d1ccc66d 1891 * Note: the CPU doing B need not be c0 or c1
8643cda5
PZ
1892 *
1893 * Example:
1894 *
1895 * CPU0 CPU1 CPU2
1896 *
1897 * LOCK rq(0)->lock
1898 * sched-out X
1899 * sched-in Y
1900 * UNLOCK rq(0)->lock
1901 *
1902 * LOCK rq(0)->lock // orders against CPU0
1903 * dequeue X
1904 * UNLOCK rq(0)->lock
1905 *
1906 * LOCK rq(1)->lock
1907 * enqueue X
1908 * UNLOCK rq(1)->lock
1909 *
1910 * LOCK rq(1)->lock // orders against CPU2
1911 * sched-out Z
1912 * sched-in X
1913 * UNLOCK rq(1)->lock
1914 *
1915 *
1916 * BLOCKING -- aka. SLEEP + WAKEUP
1917 *
1918 * For blocking we (obviously) need to provide the same guarantee as for
1919 * migration. However the means are completely different as there is no lock
1920 * chain to provide order. Instead we do:
1921 *
1922 * 1) smp_store_release(X->on_cpu, 0)
1f03e8d2 1923 * 2) smp_cond_load_acquire(!X->on_cpu)
8643cda5
PZ
1924 *
1925 * Example:
1926 *
1927 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
1928 *
1929 * LOCK rq(0)->lock LOCK X->pi_lock
1930 * dequeue X
1931 * sched-out X
1932 * smp_store_release(X->on_cpu, 0);
1933 *
1f03e8d2 1934 * smp_cond_load_acquire(&X->on_cpu, !VAL);
8643cda5
PZ
1935 * X->state = WAKING
1936 * set_task_cpu(X,2)
1937 *
1938 * LOCK rq(2)->lock
1939 * enqueue X
1940 * X->state = RUNNING
1941 * UNLOCK rq(2)->lock
1942 *
1943 * LOCK rq(2)->lock // orders against CPU1
1944 * sched-out Z
1945 * sched-in X
1946 * UNLOCK rq(2)->lock
1947 *
1948 * UNLOCK X->pi_lock
1949 * UNLOCK rq(0)->lock
1950 *
1951 *
1952 * However; for wakeups there is a second guarantee we must provide, namely we
1953 * must observe the state that lead to our wakeup. That is, not only must our
1954 * task observe its own prior state, it must also observe the stores prior to
1955 * its wakeup.
1956 *
1957 * This means that any means of doing remote wakeups must order the CPU doing
1958 * the wakeup against the CPU the task is going to end up running on. This,
1959 * however, is already required for the regular Program-Order guarantee above,
1f03e8d2 1960 * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
8643cda5
PZ
1961 *
1962 */
1963
9ed3811a 1964/**
1da177e4 1965 * try_to_wake_up - wake up a thread
9ed3811a 1966 * @p: the thread to be awakened
1da177e4 1967 * @state: the mask of task states that can be woken
9ed3811a 1968 * @wake_flags: wake modifier flags (WF_*)
1da177e4 1969 *
a2250238 1970 * If (@state & @p->state) @p->state = TASK_RUNNING.
1da177e4 1971 *
a2250238
PZ
1972 * If the task was not queued/runnable, also place it back on a runqueue.
1973 *
1974 * Atomic against schedule() which would dequeue a task, also see
1975 * set_current_state().
1976 *
1977 * Return: %true if @p->state changes (an actual wakeup was done),
1978 * %false otherwise.
1da177e4 1979 */
e4a52bcb
PZ
1980static int
1981try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1da177e4 1982{
1da177e4 1983 unsigned long flags;
c05fbafb 1984 int cpu, success = 0;
2398f2c6 1985
e0acd0a6
ON
1986 /*
1987 * If we are going to wake up a thread waiting for CONDITION we
1988 * need to ensure that CONDITION=1 done by the caller can not be
1989 * reordered with p->state check below. This pairs with mb() in
1990 * set_current_state() the waiting thread does.
1991 */
013fdb80 1992 raw_spin_lock_irqsave(&p->pi_lock, flags);
d89e588c 1993 smp_mb__after_spinlock();
e9c84311 1994 if (!(p->state & state))
1da177e4
LT
1995 goto out;
1996
fbd705a0
PZ
1997 trace_sched_waking(p);
1998
d1ccc66d
IM
1999 /* We're going to change ->state: */
2000 success = 1;
1da177e4 2001 cpu = task_cpu(p);
1da177e4 2002
135e8c92
BS
2003 /*
2004 * Ensure we load p->on_rq _after_ p->state, otherwise it would
2005 * be possible to, falsely, observe p->on_rq == 0 and get stuck
2006 * in smp_cond_load_acquire() below.
2007 *
2008 * sched_ttwu_pending() try_to_wake_up()
2009 * [S] p->on_rq = 1; [L] P->state
2010 * UNLOCK rq->lock -----.
2011 * \
2012 * +--- RMB
2013 * schedule() /
2014 * LOCK rq->lock -----'
2015 * UNLOCK rq->lock
2016 *
2017 * [task p]
2018 * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
2019 *
2020 * Pairs with the UNLOCK+LOCK on rq->lock from the
2021 * last wakeup of our task and the schedule that got our task
2022 * current.
2023 */
2024 smp_rmb();
c05fbafb
PZ
2025 if (p->on_rq && ttwu_remote(p, wake_flags))
2026 goto stat;
1da177e4 2027
1da177e4 2028#ifdef CONFIG_SMP
ecf7d01c
PZ
2029 /*
2030 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2031 * possible to, falsely, observe p->on_cpu == 0.
2032 *
2033 * One must be running (->on_cpu == 1) in order to remove oneself
2034 * from the runqueue.
2035 *
2036 * [S] ->on_cpu = 1; [L] ->on_rq
2037 * UNLOCK rq->lock
2038 * RMB
2039 * LOCK rq->lock
2040 * [S] ->on_rq = 0; [L] ->on_cpu
2041 *
2042 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2043 * from the consecutive calls to schedule(); the first switching to our
2044 * task, the second putting it to sleep.
2045 */
2046 smp_rmb();
2047
e9c84311 2048 /*
d1ccc66d 2049 * If the owning (remote) CPU is still in the middle of schedule() with
c05fbafb 2050 * this task as prev, wait until its done referencing the task.
b75a2253
PZ
2051 *
2052 * Pairs with the smp_store_release() in finish_lock_switch().
2053 *
2054 * This ensures that tasks getting woken will be fully ordered against
2055 * their previous state and preserve Program Order.
0970d299 2056 */
1f03e8d2 2057 smp_cond_load_acquire(&p->on_cpu, !VAL);
1da177e4 2058
a8e4f2ea 2059 p->sched_contributes_to_load = !!task_contributes_to_load(p);
e9c84311 2060 p->state = TASK_WAKING;
e7693a36 2061
e33a9bba 2062 if (p->in_iowait) {
c96f5471 2063 delayacct_blkio_end(p);
e33a9bba
TH
2064 atomic_dec(&task_rq(p)->nr_iowait);
2065 }
2066
ac66f547 2067 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
f339b9dc
PZ
2068 if (task_cpu(p) != cpu) {
2069 wake_flags |= WF_MIGRATED;
e4a52bcb 2070 set_task_cpu(p, cpu);
f339b9dc 2071 }
e33a9bba
TH
2072
2073#else /* CONFIG_SMP */
2074
2075 if (p->in_iowait) {
c96f5471 2076 delayacct_blkio_end(p);
e33a9bba
TH
2077 atomic_dec(&task_rq(p)->nr_iowait);
2078 }
2079
1da177e4 2080#endif /* CONFIG_SMP */
1da177e4 2081
b5179ac7 2082 ttwu_queue(p, cpu, wake_flags);
c05fbafb 2083stat:
4fa8d299 2084 ttwu_stat(p, cpu, wake_flags);
1da177e4 2085out:
013fdb80 2086 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
2087
2088 return success;
2089}
2090
21aa9af0
TH
2091/**
2092 * try_to_wake_up_local - try to wake up a local task with rq lock held
2093 * @p: the thread to be awakened
bf50f0e8 2094 * @rf: request-queue flags for pinning
21aa9af0 2095 *
2acca55e 2096 * Put @p on the run-queue if it's not already there. The caller must
21aa9af0 2097 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2acca55e 2098 * the current task.
21aa9af0 2099 */
d8ac8971 2100static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
21aa9af0
TH
2101{
2102 struct rq *rq = task_rq(p);
21aa9af0 2103
383efcd0
TH
2104 if (WARN_ON_ONCE(rq != this_rq()) ||
2105 WARN_ON_ONCE(p == current))
2106 return;
2107
21aa9af0
TH
2108 lockdep_assert_held(&rq->lock);
2109
2acca55e 2110 if (!raw_spin_trylock(&p->pi_lock)) {
cbce1a68
PZ
2111 /*
2112 * This is OK, because current is on_cpu, which avoids it being
2113 * picked for load-balance and preemption/IRQs are still
2114 * disabled avoiding further scheduler activity on it and we've
2115 * not yet picked a replacement task.
2116 */
8a8c69c3 2117 rq_unlock(rq, rf);
2acca55e 2118 raw_spin_lock(&p->pi_lock);
8a8c69c3 2119 rq_relock(rq, rf);
2acca55e
PZ
2120 }
2121
21aa9af0 2122 if (!(p->state & TASK_NORMAL))
2acca55e 2123 goto out;
21aa9af0 2124
fbd705a0
PZ
2125 trace_sched_waking(p);
2126
e33a9bba
TH
2127 if (!task_on_rq_queued(p)) {
2128 if (p->in_iowait) {
c96f5471 2129 delayacct_blkio_end(p);
e33a9bba
TH
2130 atomic_dec(&rq->nr_iowait);
2131 }
bce4dc80 2132 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
e33a9bba 2133 }
d7c01d27 2134
d8ac8971 2135 ttwu_do_wakeup(rq, p, 0, rf);
4fa8d299 2136 ttwu_stat(p, smp_processor_id(), 0);
2acca55e
PZ
2137out:
2138 raw_spin_unlock(&p->pi_lock);
21aa9af0
TH
2139}
2140
50fa610a
DH
2141/**
2142 * wake_up_process - Wake up a specific process
2143 * @p: The process to be woken up.
2144 *
2145 * Attempt to wake up the nominated process and move it to the set of runnable
e69f6186
YB
2146 * processes.
2147 *
2148 * Return: 1 if the process was woken up, 0 if it was already running.
50fa610a
DH
2149 *
2150 * It may be assumed that this function implies a write memory barrier before
2151 * changing the task state if and only if any tasks are woken up.
2152 */
7ad5b3a5 2153int wake_up_process(struct task_struct *p)
1da177e4 2154{
9067ac85 2155 return try_to_wake_up(p, TASK_NORMAL, 0);
1da177e4 2156}
1da177e4
LT
2157EXPORT_SYMBOL(wake_up_process);
2158
7ad5b3a5 2159int wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
2160{
2161 return try_to_wake_up(p, state, 0);
2162}
2163
1da177e4
LT
2164/*
2165 * Perform scheduler related setup for a newly forked process p.
2166 * p is forked by current.
dd41f596
IM
2167 *
2168 * __sched_fork() is basic setup used by init_idle() too:
2169 */
5e1576ed 2170static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 2171{
fd2f4419
PZ
2172 p->on_rq = 0;
2173
2174 p->se.on_rq = 0;
dd41f596
IM
2175 p->se.exec_start = 0;
2176 p->se.sum_exec_runtime = 0;
f6cf891c 2177 p->se.prev_sum_exec_runtime = 0;
6c594c21 2178 p->se.nr_migrations = 0;
da7a735e 2179 p->se.vruntime = 0;
fd2f4419 2180 INIT_LIST_HEAD(&p->se.group_node);
6cfb0d5d 2181
ad936d86
BP
2182#ifdef CONFIG_FAIR_GROUP_SCHED
2183 p->se.cfs_rq = NULL;
2184#endif
2185
6cfb0d5d 2186#ifdef CONFIG_SCHEDSTATS
cb251765 2187 /* Even if schedstat is disabled, there should not be garbage */
41acab88 2188 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
6cfb0d5d 2189#endif
476d139c 2190
aab03e05 2191 RB_CLEAR_NODE(&p->dl.rb_node);
40767b0d 2192 init_dl_task_timer(&p->dl);
209a0cbd 2193 init_dl_inactive_task_timer(&p->dl);
a5e7be3b 2194 __dl_clear_params(p);
aab03e05 2195
fa717060 2196 INIT_LIST_HEAD(&p->rt.run_list);
ff77e468
PZ
2197 p->rt.timeout = 0;
2198 p->rt.time_slice = sched_rr_timeslice;
2199 p->rt.on_rq = 0;
2200 p->rt.on_list = 0;
476d139c 2201
e107be36
AK
2202#ifdef CONFIG_PREEMPT_NOTIFIERS
2203 INIT_HLIST_HEAD(&p->preempt_notifiers);
2204#endif
cbee9f88
PZ
2205
2206#ifdef CONFIG_NUMA_BALANCING
2207 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
7e8d16b6 2208 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
cbee9f88
PZ
2209 p->mm->numa_scan_seq = 0;
2210 }
2211
5e1576ed
RR
2212 if (clone_flags & CLONE_VM)
2213 p->numa_preferred_nid = current->numa_preferred_nid;
2214 else
2215 p->numa_preferred_nid = -1;
2216
cbee9f88
PZ
2217 p->node_stamp = 0ULL;
2218 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
4b96a29b 2219 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
cbee9f88 2220 p->numa_work.next = &p->numa_work;
44dba3d5 2221 p->numa_faults = NULL;
7e2703e6
RR
2222 p->last_task_numa_placement = 0;
2223 p->last_sum_exec_runtime = 0;
8c8a743c 2224
8c8a743c 2225 p->numa_group = NULL;
cbee9f88 2226#endif /* CONFIG_NUMA_BALANCING */
dd41f596
IM
2227}
2228
2a595721
SD
2229DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2230
1a687c2e 2231#ifdef CONFIG_NUMA_BALANCING
c3b9bc5b 2232
1a687c2e
MG
2233void set_numabalancing_state(bool enabled)
2234{
2235 if (enabled)
2a595721 2236 static_branch_enable(&sched_numa_balancing);
1a687c2e 2237 else
2a595721 2238 static_branch_disable(&sched_numa_balancing);
1a687c2e 2239}
54a43d54
AK
2240
2241#ifdef CONFIG_PROC_SYSCTL
2242int sysctl_numa_balancing(struct ctl_table *table, int write,
2243 void __user *buffer, size_t *lenp, loff_t *ppos)
2244{
2245 struct ctl_table t;
2246 int err;
2a595721 2247 int state = static_branch_likely(&sched_numa_balancing);
54a43d54
AK
2248
2249 if (write && !capable(CAP_SYS_ADMIN))
2250 return -EPERM;
2251
2252 t = *table;
2253 t.data = &state;
2254 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2255 if (err < 0)
2256 return err;
2257 if (write)
2258 set_numabalancing_state(state);
2259 return err;
2260}
2261#endif
2262#endif
dd41f596 2263
4698f88c
JP
2264#ifdef CONFIG_SCHEDSTATS
2265
cb251765 2266DEFINE_STATIC_KEY_FALSE(sched_schedstats);
4698f88c 2267static bool __initdata __sched_schedstats = false;
cb251765 2268
cb251765
MG
2269static void set_schedstats(bool enabled)
2270{
2271 if (enabled)
2272 static_branch_enable(&sched_schedstats);
2273 else
2274 static_branch_disable(&sched_schedstats);
2275}
2276
2277void force_schedstat_enabled(void)
2278{
2279 if (!schedstat_enabled()) {
2280 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2281 static_branch_enable(&sched_schedstats);
2282 }
2283}
2284
2285static int __init setup_schedstats(char *str)
2286{
2287 int ret = 0;
2288 if (!str)
2289 goto out;
2290
4698f88c
JP
2291 /*
2292 * This code is called before jump labels have been set up, so we can't
2293 * change the static branch directly just yet. Instead set a temporary
2294 * variable so init_schedstats() can do it later.
2295 */
cb251765 2296 if (!strcmp(str, "enable")) {
4698f88c 2297 __sched_schedstats = true;
cb251765
MG
2298 ret = 1;
2299 } else if (!strcmp(str, "disable")) {
4698f88c 2300 __sched_schedstats = false;
cb251765
MG
2301 ret = 1;
2302 }
2303out:
2304 if (!ret)
2305 pr_warn("Unable to parse schedstats=\n");
2306
2307 return ret;
2308}
2309__setup("schedstats=", setup_schedstats);
2310
4698f88c
JP
2311static void __init init_schedstats(void)
2312{
2313 set_schedstats(__sched_schedstats);
2314}
2315
cb251765
MG
2316#ifdef CONFIG_PROC_SYSCTL
2317int sysctl_schedstats(struct ctl_table *table, int write,
2318 void __user *buffer, size_t *lenp, loff_t *ppos)
2319{
2320 struct ctl_table t;
2321 int err;
2322 int state = static_branch_likely(&sched_schedstats);
2323
2324 if (write && !capable(CAP_SYS_ADMIN))
2325 return -EPERM;
2326
2327 t = *table;
2328 t.data = &state;
2329 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2330 if (err < 0)
2331 return err;
2332 if (write)
2333 set_schedstats(state);
2334 return err;
2335}
4698f88c
JP
2336#endif /* CONFIG_PROC_SYSCTL */
2337#else /* !CONFIG_SCHEDSTATS */
2338static inline void init_schedstats(void) {}
2339#endif /* CONFIG_SCHEDSTATS */
dd41f596
IM
2340
2341/*
2342 * fork()/clone()-time setup:
2343 */
aab03e05 2344int sched_fork(unsigned long clone_flags, struct task_struct *p)
dd41f596 2345{
0122ec5b 2346 unsigned long flags;
dd41f596
IM
2347 int cpu = get_cpu();
2348
5e1576ed 2349 __sched_fork(clone_flags, p);
06b83b5f 2350 /*
7dc603c9 2351 * We mark the process as NEW here. This guarantees that
06b83b5f
PZ
2352 * nobody will actually run it, and a signal or other external
2353 * event cannot wake it up and insert it on the runqueue either.
2354 */
7dc603c9 2355 p->state = TASK_NEW;
dd41f596 2356
c350a04e
MG
2357 /*
2358 * Make sure we do not leak PI boosting priority to the child.
2359 */
2360 p->prio = current->normal_prio;
2361
b9dc29e7
MG
2362 /*
2363 * Revert to default priority/policy on fork if requested.
2364 */
2365 if (unlikely(p->sched_reset_on_fork)) {
aab03e05 2366 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
b9dc29e7 2367 p->policy = SCHED_NORMAL;
6c697bdf 2368 p->static_prio = NICE_TO_PRIO(0);
c350a04e
MG
2369 p->rt_priority = 0;
2370 } else if (PRIO_TO_NICE(p->static_prio) < 0)
2371 p->static_prio = NICE_TO_PRIO(0);
2372
2373 p->prio = p->normal_prio = __normal_prio(p);
9059393e 2374 set_load_weight(p, false);
6c697bdf 2375
b9dc29e7
MG
2376 /*
2377 * We don't need the reset flag anymore after the fork. It has
2378 * fulfilled its duty:
2379 */
2380 p->sched_reset_on_fork = 0;
2381 }
ca94c442 2382
aab03e05
DF
2383 if (dl_prio(p->prio)) {
2384 put_cpu();
2385 return -EAGAIN;
2386 } else if (rt_prio(p->prio)) {
2387 p->sched_class = &rt_sched_class;
2388 } else {
2ddbf952 2389 p->sched_class = &fair_sched_class;
aab03e05 2390 }
b29739f9 2391
7dc603c9 2392 init_entity_runnable_average(&p->se);
cd29fe6f 2393
86951599
PZ
2394 /*
2395 * The child is not yet in the pid-hash so no cgroup attach races,
2396 * and the cgroup is pinned to this child due to cgroup_fork()
2397 * is ran before sched_fork().
2398 *
2399 * Silence PROVE_RCU.
2400 */
0122ec5b 2401 raw_spin_lock_irqsave(&p->pi_lock, flags);
e210bffd 2402 /*
d1ccc66d 2403 * We're setting the CPU for the first time, we don't migrate,
e210bffd
PZ
2404 * so use __set_task_cpu().
2405 */
2406 __set_task_cpu(p, cpu);
2407 if (p->sched_class->task_fork)
2408 p->sched_class->task_fork(p);
0122ec5b 2409 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5f3edc1b 2410
f6db8347 2411#ifdef CONFIG_SCHED_INFO
dd41f596 2412 if (likely(sched_info_on()))
52f17b6c 2413 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 2414#endif
3ca7a440
PZ
2415#if defined(CONFIG_SMP)
2416 p->on_cpu = 0;
4866cde0 2417#endif
01028747 2418 init_task_preempt_count(p);
806c09a7 2419#ifdef CONFIG_SMP
917b627d 2420 plist_node_init(&p->pushable_tasks, MAX_PRIO);
1baca4ce 2421 RB_CLEAR_NODE(&p->pushable_dl_tasks);
806c09a7 2422#endif
917b627d 2423
476d139c 2424 put_cpu();
aab03e05 2425 return 0;
1da177e4
LT
2426}
2427
332ac17e
DF
2428unsigned long to_ratio(u64 period, u64 runtime)
2429{
2430 if (runtime == RUNTIME_INF)
c52f14d3 2431 return BW_UNIT;
332ac17e
DF
2432
2433 /*
2434 * Doing this here saves a lot of checks in all
2435 * the calling paths, and returning zero seems
2436 * safe for them anyway.
2437 */
2438 if (period == 0)
2439 return 0;
2440
c52f14d3 2441 return div64_u64(runtime << BW_SHIFT, period);
332ac17e
DF
2442}
2443
1da177e4
LT
2444/*
2445 * wake_up_new_task - wake up a newly created task for the first time.
2446 *
2447 * This function will do some initial scheduler statistics housekeeping
2448 * that must be done for every newly created context, then puts the task
2449 * on the runqueue and wakes it.
2450 */
3e51e3ed 2451void wake_up_new_task(struct task_struct *p)
1da177e4 2452{
eb580751 2453 struct rq_flags rf;
dd41f596 2454 struct rq *rq;
fabf318e 2455
eb580751 2456 raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
7dc603c9 2457 p->state = TASK_RUNNING;
fabf318e
PZ
2458#ifdef CONFIG_SMP
2459 /*
2460 * Fork balancing, do it here and not earlier because:
2461 * - cpus_allowed can change in the fork path
d1ccc66d 2462 * - any previously selected CPU might disappear through hotplug
e210bffd
PZ
2463 *
2464 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2465 * as we're not fully set-up yet.
fabf318e 2466 */
e210bffd 2467 __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
0017d735 2468#endif
b7fa30c9 2469 rq = __task_rq_lock(p, &rf);
4126bad6 2470 update_rq_clock(rq);
2b8c41da 2471 post_init_entity_util_avg(&p->se);
0017d735 2472
7a57f32a 2473 activate_task(rq, p, ENQUEUE_NOCLOCK);
da0c1e65 2474 p->on_rq = TASK_ON_RQ_QUEUED;
fbd705a0 2475 trace_sched_wakeup_new(p);
a7558e01 2476 check_preempt_curr(rq, p, WF_FORK);
9a897c5a 2477#ifdef CONFIG_SMP
0aaafaab
PZ
2478 if (p->sched_class->task_woken) {
2479 /*
2480 * Nothing relies on rq->lock after this, so its fine to
2481 * drop it.
2482 */
d8ac8971 2483 rq_unpin_lock(rq, &rf);
efbbd05a 2484 p->sched_class->task_woken(rq, p);
d8ac8971 2485 rq_repin_lock(rq, &rf);
0aaafaab 2486 }
9a897c5a 2487#endif
eb580751 2488 task_rq_unlock(rq, p, &rf);
1da177e4
LT
2489}
2490
e107be36
AK
2491#ifdef CONFIG_PREEMPT_NOTIFIERS
2492
1cde2930
PZ
2493static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
2494
2ecd9d29
PZ
2495void preempt_notifier_inc(void)
2496{
2497 static_key_slow_inc(&preempt_notifier_key);
2498}
2499EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2500
2501void preempt_notifier_dec(void)
2502{
2503 static_key_slow_dec(&preempt_notifier_key);
2504}
2505EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2506
e107be36 2507/**
80dd99b3 2508 * preempt_notifier_register - tell me when current is being preempted & rescheduled
421cee29 2509 * @notifier: notifier struct to register
e107be36
AK
2510 */
2511void preempt_notifier_register(struct preempt_notifier *notifier)
2512{
2ecd9d29
PZ
2513 if (!static_key_false(&preempt_notifier_key))
2514 WARN(1, "registering preempt_notifier while notifiers disabled\n");
2515
e107be36
AK
2516 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2517}
2518EXPORT_SYMBOL_GPL(preempt_notifier_register);
2519
2520/**
2521 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 2522 * @notifier: notifier struct to unregister
e107be36 2523 *
d84525a8 2524 * This is *not* safe to call from within a preemption notifier.
e107be36
AK
2525 */
2526void preempt_notifier_unregister(struct preempt_notifier *notifier)
2527{
2528 hlist_del(&notifier->link);
2529}
2530EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2531
1cde2930 2532static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
2533{
2534 struct preempt_notifier *notifier;
e107be36 2535
b67bfe0d 2536 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
2537 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2538}
2539
1cde2930
PZ
2540static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2541{
2542 if (static_key_false(&preempt_notifier_key))
2543 __fire_sched_in_preempt_notifiers(curr);
2544}
2545
e107be36 2546static void
1cde2930
PZ
2547__fire_sched_out_preempt_notifiers(struct task_struct *curr,
2548 struct task_struct *next)
e107be36
AK
2549{
2550 struct preempt_notifier *notifier;
e107be36 2551
b67bfe0d 2552 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
e107be36
AK
2553 notifier->ops->sched_out(notifier, next);
2554}
2555
1cde2930
PZ
2556static __always_inline void
2557fire_sched_out_preempt_notifiers(struct task_struct *curr,
2558 struct task_struct *next)
2559{
2560 if (static_key_false(&preempt_notifier_key))
2561 __fire_sched_out_preempt_notifiers(curr, next);
2562}
2563
6d6bc0ad 2564#else /* !CONFIG_PREEMPT_NOTIFIERS */
e107be36 2565
1cde2930 2566static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
e107be36
AK
2567{
2568}
2569
1cde2930 2570static inline void
e107be36
AK
2571fire_sched_out_preempt_notifiers(struct task_struct *curr,
2572 struct task_struct *next)
2573{
2574}
2575
6d6bc0ad 2576#endif /* CONFIG_PREEMPT_NOTIFIERS */
e107be36 2577
4866cde0
NP
2578/**
2579 * prepare_task_switch - prepare to switch tasks
2580 * @rq: the runqueue preparing to switch
421cee29 2581 * @prev: the current task that is being switched out
4866cde0
NP
2582 * @next: the task we are going to switch to.
2583 *
2584 * This is called with the rq lock held and interrupts off. It must
2585 * be paired with a subsequent finish_task_switch after the context
2586 * switch.
2587 *
2588 * prepare_task_switch sets up locking and calls architecture specific
2589 * hooks.
2590 */
e107be36
AK
2591static inline void
2592prepare_task_switch(struct rq *rq, struct task_struct *prev,
2593 struct task_struct *next)
4866cde0 2594{
43148951 2595 sched_info_switch(rq, prev, next);
fe4b04fa 2596 perf_event_task_sched_out(prev, next);
e107be36 2597 fire_sched_out_preempt_notifiers(prev, next);
4866cde0
NP
2598 prepare_lock_switch(rq, next);
2599 prepare_arch_switch(next);
2600}
2601
1da177e4
LT
2602/**
2603 * finish_task_switch - clean up after a task-switch
2604 * @prev: the thread we just switched away from.
2605 *
4866cde0
NP
2606 * finish_task_switch must be called after the context switch, paired
2607 * with a prepare_task_switch call before the context switch.
2608 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2609 * and do any other architecture-specific cleanup actions.
1da177e4
LT
2610 *
2611 * Note that we may have delayed dropping an mm in context_switch(). If
41a2d6cf 2612 * so, we finish that here outside of the runqueue lock. (Doing it
1da177e4
LT
2613 * with the lock held can cause deadlocks; see schedule() for
2614 * details.)
dfa50b60
ON
2615 *
2616 * The context switch have flipped the stack from under us and restored the
2617 * local variables which were saved when this task called schedule() in the
2618 * past. prev == current is still correct but we need to recalculate this_rq
2619 * because prev may have moved to another CPU.
1da177e4 2620 */
dfa50b60 2621static struct rq *finish_task_switch(struct task_struct *prev)
1da177e4
LT
2622 __releases(rq->lock)
2623{
dfa50b60 2624 struct rq *rq = this_rq();
1da177e4 2625 struct mm_struct *mm = rq->prev_mm;
55a101f8 2626 long prev_state;
1da177e4 2627
609ca066
PZ
2628 /*
2629 * The previous task will have left us with a preempt_count of 2
2630 * because it left us after:
2631 *
2632 * schedule()
2633 * preempt_disable(); // 1
2634 * __schedule()
2635 * raw_spin_lock_irq(&rq->lock) // 2
2636 *
2637 * Also, see FORK_PREEMPT_COUNT.
2638 */
e2bf1c4b
PZ
2639 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2640 "corrupted preempt_count: %s/%d/0x%x\n",
2641 current->comm, current->pid, preempt_count()))
2642 preempt_count_set(FORK_PREEMPT_COUNT);
609ca066 2643
1da177e4
LT
2644 rq->prev_mm = NULL;
2645
2646 /*
2647 * A task struct has one reference for the use as "current".
c394cc9f 2648 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
2649 * schedule one last time. The schedule call will never return, and
2650 * the scheduled task must drop that reference.
95913d97
PZ
2651 *
2652 * We must observe prev->state before clearing prev->on_cpu (in
2653 * finish_lock_switch), otherwise a concurrent wakeup can get prev
2654 * running on another CPU and we could rave with its RUNNING -> DEAD
2655 * transition, resulting in a double drop.
1da177e4 2656 */
55a101f8 2657 prev_state = prev->state;
bf9fae9f 2658 vtime_task_switch(prev);
a8d757ef 2659 perf_event_task_sched_in(prev, current);
22e4ebb9
MD
2660 /*
2661 * The membarrier system call requires a full memory barrier
2662 * after storing to rq->curr, before going back to user-space.
2663 *
2664 * TODO: This smp_mb__after_unlock_lock can go away if PPC end
2665 * up adding a full barrier to switch_mm(), or we should figure
2666 * out if a smp_mb__after_unlock_lock is really the proper API
2667 * to use.
2668 */
2669 smp_mb__after_unlock_lock();
4866cde0 2670 finish_lock_switch(rq, prev);
01f23e16 2671 finish_arch_post_lock_switch();
e8fa1362 2672
e107be36 2673 fire_sched_in_preempt_notifiers(current);
1da177e4
LT
2674 if (mm)
2675 mmdrop(mm);
605478e2
PZ
2676 if (unlikely(prev_state & (TASK_DEAD|TASK_PARKED))) {
2677 switch (prev_state) {
2678 case TASK_DEAD:
2679 if (prev->sched_class->task_dead)
2680 prev->sched_class->task_dead(prev);
2681
2682 /*
2683 * Remove function-return probe instances associated with this
2684 * task and put them back on the free list.
2685 */
2686 kprobe_flush_task(prev);
2687
2688 /* Task is done with its stack. */
2689 put_task_stack(prev);
2690
2691 put_task_struct(prev);
2692 break;
68f24b08 2693
605478e2
PZ
2694 case TASK_PARKED:
2695 kthread_park_complete(prev);
2696 break;
2697 }
c6fd91f0 2698 }
99e5ada9 2699
de734f89 2700 tick_nohz_task_switch();
dfa50b60 2701 return rq;
1da177e4
LT
2702}
2703
3f029d3c
GH
2704#ifdef CONFIG_SMP
2705
3f029d3c 2706/* rq->lock is NOT held, but preemption is disabled */
e3fca9e7 2707static void __balance_callback(struct rq *rq)
3f029d3c 2708{
e3fca9e7
PZ
2709 struct callback_head *head, *next;
2710 void (*func)(struct rq *rq);
2711 unsigned long flags;
3f029d3c 2712
e3fca9e7
PZ
2713 raw_spin_lock_irqsave(&rq->lock, flags);
2714 head = rq->balance_callback;
2715 rq->balance_callback = NULL;
2716 while (head) {
2717 func = (void (*)(struct rq *))head->func;
2718 next = head->next;
2719 head->next = NULL;
2720 head = next;
3f029d3c 2721
e3fca9e7 2722 func(rq);
3f029d3c 2723 }
e3fca9e7
PZ
2724 raw_spin_unlock_irqrestore(&rq->lock, flags);
2725}
2726
2727static inline void balance_callback(struct rq *rq)
2728{
2729 if (unlikely(rq->balance_callback))
2730 __balance_callback(rq);
3f029d3c
GH
2731}
2732
2733#else
da19ab51 2734
e3fca9e7 2735static inline void balance_callback(struct rq *rq)
3f029d3c 2736{
1da177e4
LT
2737}
2738
3f029d3c
GH
2739#endif
2740
1da177e4
LT
2741/**
2742 * schedule_tail - first thing a freshly forked thread must call.
2743 * @prev: the thread we just switched away from.
2744 */
722a9f92 2745asmlinkage __visible void schedule_tail(struct task_struct *prev)
1da177e4
LT
2746 __releases(rq->lock)
2747{
1a43a14a 2748 struct rq *rq;
da19ab51 2749
609ca066
PZ
2750 /*
2751 * New tasks start with FORK_PREEMPT_COUNT, see there and
2752 * finish_task_switch() for details.
2753 *
2754 * finish_task_switch() will drop rq->lock() and lower preempt_count
2755 * and the preempt_enable() will end up enabling preemption (on
2756 * PREEMPT_COUNT kernels).
2757 */
2758
dfa50b60 2759 rq = finish_task_switch(prev);
e3fca9e7 2760 balance_callback(rq);
1a43a14a 2761 preempt_enable();
70b97a7f 2762
1da177e4 2763 if (current->set_child_tid)
b488893a 2764 put_user(task_pid_vnr(current), current->set_child_tid);
1da177e4
LT
2765}
2766
2767/*
dfa50b60 2768 * context_switch - switch to the new MM and the new thread's register state.
1da177e4 2769 */
04936948 2770static __always_inline struct rq *
70b97a7f 2771context_switch(struct rq *rq, struct task_struct *prev,
d8ac8971 2772 struct task_struct *next, struct rq_flags *rf)
1da177e4 2773{
dd41f596 2774 struct mm_struct *mm, *oldmm;
1da177e4 2775
e107be36 2776 prepare_task_switch(rq, prev, next);
fe4b04fa 2777
dd41f596
IM
2778 mm = next->mm;
2779 oldmm = prev->active_mm;
9226d125
ZA
2780 /*
2781 * For paravirt, this is coupled with an exit in switch_to to
2782 * combine the page table reload and the switch backend into
2783 * one hypercall.
2784 */
224101ed 2785 arch_start_context_switch(prev);
9226d125 2786
31915ab4 2787 if (!mm) {
1da177e4 2788 next->active_mm = oldmm;
f1f10076 2789 mmgrab(oldmm);
1da177e4
LT
2790 enter_lazy_tlb(oldmm, next);
2791 } else
f98db601 2792 switch_mm_irqs_off(oldmm, mm, next);
1da177e4 2793
31915ab4 2794 if (!prev->mm) {
1da177e4 2795 prev->active_mm = NULL;
1da177e4
LT
2796 rq->prev_mm = oldmm;
2797 }
92509b73 2798
cb42c9a3 2799 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
92509b73 2800
3a5f5e48
IM
2801 /*
2802 * Since the runqueue lock will be released by the next
2803 * task (which is an invalid locking op but in the case
2804 * of the scheduler it's an obvious special-case), so we
2805 * do an early lockdep release here:
2806 */
d8ac8971 2807 rq_unpin_lock(rq, rf);
8a25d5de 2808 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1da177e4
LT
2809
2810 /* Here we just switch the register state and the stack. */
2811 switch_to(prev, next, prev);
dd41f596 2812 barrier();
dfa50b60
ON
2813
2814 return finish_task_switch(prev);
1da177e4
LT
2815}
2816
2817/*
1c3e8264 2818 * nr_running and nr_context_switches:
1da177e4
LT
2819 *
2820 * externally visible scheduler statistics: current number of runnable
1c3e8264 2821 * threads, total number of context switches performed since bootup.
1da177e4
LT
2822 */
2823unsigned long nr_running(void)
2824{
2825 unsigned long i, sum = 0;
2826
2827 for_each_online_cpu(i)
2828 sum += cpu_rq(i)->nr_running;
2829
2830 return sum;
f711f609 2831}
1da177e4 2832
2ee507c4 2833/*
d1ccc66d 2834 * Check if only the current task is running on the CPU.
00cc1633
DD
2835 *
2836 * Caution: this function does not check that the caller has disabled
2837 * preemption, thus the result might have a time-of-check-to-time-of-use
2838 * race. The caller is responsible to use it correctly, for example:
2839 *
2840 * - from a non-preemptable section (of course)
2841 *
2842 * - from a thread that is bound to a single CPU
2843 *
2844 * - in a loop with very short iterations (e.g. a polling loop)
2ee507c4
TC
2845 */
2846bool single_task_running(void)
2847{
00cc1633 2848 return raw_rq()->nr_running == 1;
2ee507c4
TC
2849}
2850EXPORT_SYMBOL(single_task_running);
2851
1da177e4 2852unsigned long long nr_context_switches(void)
46cb4b7c 2853{
cc94abfc
SR
2854 int i;
2855 unsigned long long sum = 0;
46cb4b7c 2856
0a945022 2857 for_each_possible_cpu(i)
1da177e4 2858 sum += cpu_rq(i)->nr_switches;
46cb4b7c 2859
1da177e4
LT
2860 return sum;
2861}
483b4ee6 2862
e33a9bba
TH
2863/*
2864 * IO-wait accounting, and how its mostly bollocks (on SMP).
2865 *
2866 * The idea behind IO-wait account is to account the idle time that we could
2867 * have spend running if it were not for IO. That is, if we were to improve the
2868 * storage performance, we'd have a proportional reduction in IO-wait time.
2869 *
2870 * This all works nicely on UP, where, when a task blocks on IO, we account
2871 * idle time as IO-wait, because if the storage were faster, it could've been
2872 * running and we'd not be idle.
2873 *
2874 * This has been extended to SMP, by doing the same for each CPU. This however
2875 * is broken.
2876 *
2877 * Imagine for instance the case where two tasks block on one CPU, only the one
2878 * CPU will have IO-wait accounted, while the other has regular idle. Even
2879 * though, if the storage were faster, both could've ran at the same time,
2880 * utilising both CPUs.
2881 *
2882 * This means, that when looking globally, the current IO-wait accounting on
2883 * SMP is a lower bound, by reason of under accounting.
2884 *
2885 * Worse, since the numbers are provided per CPU, they are sometimes
2886 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2887 * associated with any one particular CPU, it can wake to another CPU than it
2888 * blocked on. This means the per CPU IO-wait number is meaningless.
2889 *
2890 * Task CPU affinities can make all that even more 'interesting'.
2891 */
2892
1da177e4
LT
2893unsigned long nr_iowait(void)
2894{
2895 unsigned long i, sum = 0;
483b4ee6 2896
0a945022 2897 for_each_possible_cpu(i)
1da177e4 2898 sum += atomic_read(&cpu_rq(i)->nr_iowait);
46cb4b7c 2899
1da177e4
LT
2900 return sum;
2901}
483b4ee6 2902
e33a9bba
TH
2903/*
2904 * Consumers of these two interfaces, like for example the cpufreq menu
2905 * governor are using nonsensical data. Boosting frequency for a CPU that has
2906 * IO-wait which might not even end up running the task when it does become
2907 * runnable.
2908 */
2909
8c215bd3 2910unsigned long nr_iowait_cpu(int cpu)
69d25870 2911{
8c215bd3 2912 struct rq *this = cpu_rq(cpu);
69d25870
AV
2913 return atomic_read(&this->nr_iowait);
2914}
46cb4b7c 2915
372ba8cb
MG
2916void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2917{
3289bdb4
PZ
2918 struct rq *rq = this_rq();
2919 *nr_waiters = atomic_read(&rq->nr_iowait);
2920 *load = rq->load.weight;
372ba8cb
MG
2921}
2922
dd41f596 2923#ifdef CONFIG_SMP
8a0be9ef 2924
46cb4b7c 2925/*
38022906
PZ
2926 * sched_exec - execve() is a valuable balancing opportunity, because at
2927 * this point the task has the smallest effective memory and cache footprint.
46cb4b7c 2928 */
38022906 2929void sched_exec(void)
46cb4b7c 2930{
38022906 2931 struct task_struct *p = current;
1da177e4 2932 unsigned long flags;
0017d735 2933 int dest_cpu;
46cb4b7c 2934
8f42ced9 2935 raw_spin_lock_irqsave(&p->pi_lock, flags);
ac66f547 2936 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
0017d735
PZ
2937 if (dest_cpu == smp_processor_id())
2938 goto unlock;
38022906 2939
8f42ced9 2940 if (likely(cpu_active(dest_cpu))) {
969c7921 2941 struct migration_arg arg = { p, dest_cpu };
46cb4b7c 2942
8f42ced9
PZ
2943 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2944 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
1da177e4
LT
2945 return;
2946 }
0017d735 2947unlock:
8f42ced9 2948 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4 2949}
dd41f596 2950
1da177e4
LT
2951#endif
2952
1da177e4 2953DEFINE_PER_CPU(struct kernel_stat, kstat);
3292beb3 2954DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
1da177e4
LT
2955
2956EXPORT_PER_CPU_SYMBOL(kstat);
3292beb3 2957EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
1da177e4 2958
6075620b
GG
2959/*
2960 * The function fair_sched_class.update_curr accesses the struct curr
2961 * and its field curr->exec_start; when called from task_sched_runtime(),
2962 * we observe a high rate of cache misses in practice.
2963 * Prefetching this data results in improved performance.
2964 */
2965static inline void prefetch_curr_exec_start(struct task_struct *p)
2966{
2967#ifdef CONFIG_FAIR_GROUP_SCHED
2968 struct sched_entity *curr = (&p->se)->cfs_rq->curr;
2969#else
2970 struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
2971#endif
2972 prefetch(curr);
2973 prefetch(&curr->exec_start);
2974}
2975
c5f8d995
HS
2976/*
2977 * Return accounted runtime for the task.
2978 * In case the task is currently running, return the runtime plus current's
2979 * pending runtime that have not been accounted yet.
2980 */
2981unsigned long long task_sched_runtime(struct task_struct *p)
2982{
eb580751 2983 struct rq_flags rf;
c5f8d995 2984 struct rq *rq;
6e998916 2985 u64 ns;
c5f8d995 2986
911b2898
PZ
2987#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
2988 /*
2989 * 64-bit doesn't need locks to atomically read a 64bit value.
2990 * So we have a optimization chance when the task's delta_exec is 0.
2991 * Reading ->on_cpu is racy, but this is ok.
2992 *
d1ccc66d
IM
2993 * If we race with it leaving CPU, we'll take a lock. So we're correct.
2994 * If we race with it entering CPU, unaccounted time is 0. This is
911b2898 2995 * indistinguishable from the read occurring a few cycles earlier.
4036ac15
MG
2996 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
2997 * been accounted, so we're correct here as well.
911b2898 2998 */
da0c1e65 2999 if (!p->on_cpu || !task_on_rq_queued(p))
911b2898
PZ
3000 return p->se.sum_exec_runtime;
3001#endif
3002
eb580751 3003 rq = task_rq_lock(p, &rf);
6e998916
SG
3004 /*
3005 * Must be ->curr _and_ ->on_rq. If dequeued, we would
3006 * project cycles that may never be accounted to this
3007 * thread, breaking clock_gettime().
3008 */
3009 if (task_current(rq, p) && task_on_rq_queued(p)) {
6075620b 3010 prefetch_curr_exec_start(p);
6e998916
SG
3011 update_rq_clock(rq);
3012 p->sched_class->update_curr(rq);
3013 }
3014 ns = p->se.sum_exec_runtime;
eb580751 3015 task_rq_unlock(rq, p, &rf);
c5f8d995
HS
3016
3017 return ns;
3018}
48f24c4d 3019
7835b98b
CL
3020/*
3021 * This function gets called by the timer code, with HZ frequency.
3022 * We call it with interrupts disabled.
7835b98b
CL
3023 */
3024void scheduler_tick(void)
3025{
7835b98b
CL
3026 int cpu = smp_processor_id();
3027 struct rq *rq = cpu_rq(cpu);
dd41f596 3028 struct task_struct *curr = rq->curr;
8a8c69c3 3029 struct rq_flags rf;
3e51f33f
PZ
3030
3031 sched_clock_tick();
dd41f596 3032
8a8c69c3
PZ
3033 rq_lock(rq, &rf);
3034
3e51f33f 3035 update_rq_clock(rq);
fa85ae24 3036 curr->sched_class->task_tick(rq, curr, 0);
cee1afce 3037 cpu_load_update_active(rq);
3289bdb4 3038 calc_global_load_tick(rq);
8a8c69c3
PZ
3039
3040 rq_unlock(rq, &rf);
7835b98b 3041
e9d2b064 3042 perf_event_task_tick();
e220d2dc 3043
e418e1c2 3044#ifdef CONFIG_SMP
6eb57e0d 3045 rq->idle_balance = idle_cpu(cpu);
7caff66f 3046 trigger_load_balance(rq);
e418e1c2 3047#endif
265f22a9 3048 rq_last_tick_reset(rq);
1da177e4
LT
3049}
3050
265f22a9
FW
3051#ifdef CONFIG_NO_HZ_FULL
3052/**
3053 * scheduler_tick_max_deferment
3054 *
3055 * Keep at least one tick per second when a single
3056 * active task is running because the scheduler doesn't
3057 * yet completely support full dynticks environment.
3058 *
3059 * This makes sure that uptime, CFS vruntime, load
3060 * balancing, etc... continue to move forward, even
3061 * with a very low granularity.
e69f6186
YB
3062 *
3063 * Return: Maximum deferment in nanoseconds.
265f22a9
FW
3064 */
3065u64 scheduler_tick_max_deferment(void)
3066{
3067 struct rq *rq = this_rq();
316c1608 3068 unsigned long next, now = READ_ONCE(jiffies);
265f22a9
FW
3069
3070 next = rq->last_sched_tick + HZ;
3071
3072 if (time_before_eq(next, now))
3073 return 0;
3074
8fe8ff09 3075 return jiffies_to_nsecs(next - now);
1da177e4 3076}
265f22a9 3077#endif
1da177e4 3078
7e49fcce
SR
3079#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3080 defined(CONFIG_PREEMPT_TRACER))
47252cfb
SR
3081/*
3082 * If the value passed in is equal to the current preempt count
3083 * then we just disabled preemption. Start timing the latency.
3084 */
3085static inline void preempt_latency_start(int val)
3086{
3087 if (preempt_count() == val) {
3088 unsigned long ip = get_lock_parent_ip();
3089#ifdef CONFIG_DEBUG_PREEMPT
3090 current->preempt_disable_ip = ip;
3091#endif
3092 trace_preempt_off(CALLER_ADDR0, ip);
3093 }
3094}
7e49fcce 3095
edafe3a5 3096void preempt_count_add(int val)
1da177e4 3097{
6cd8a4bb 3098#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3099 /*
3100 * Underflow?
3101 */
9a11b49a
IM
3102 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3103 return;
6cd8a4bb 3104#endif
bdb43806 3105 __preempt_count_add(val);
6cd8a4bb 3106#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3107 /*
3108 * Spinlock count overflowing soon?
3109 */
33859f7f
MOS
3110 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3111 PREEMPT_MASK - 10);
6cd8a4bb 3112#endif
47252cfb 3113 preempt_latency_start(val);
1da177e4 3114}
bdb43806 3115EXPORT_SYMBOL(preempt_count_add);
edafe3a5 3116NOKPROBE_SYMBOL(preempt_count_add);
1da177e4 3117
47252cfb
SR
3118/*
3119 * If the value passed in equals to the current preempt count
3120 * then we just enabled preemption. Stop timing the latency.
3121 */
3122static inline void preempt_latency_stop(int val)
3123{
3124 if (preempt_count() == val)
3125 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3126}
3127
edafe3a5 3128void preempt_count_sub(int val)
1da177e4 3129{
6cd8a4bb 3130#ifdef CONFIG_DEBUG_PREEMPT
1da177e4
LT
3131 /*
3132 * Underflow?
3133 */
01e3eb82 3134 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
9a11b49a 3135 return;
1da177e4
LT
3136 /*
3137 * Is the spinlock portion underflowing?
3138 */
9a11b49a
IM
3139 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3140 !(preempt_count() & PREEMPT_MASK)))
3141 return;
6cd8a4bb 3142#endif
9a11b49a 3143
47252cfb 3144 preempt_latency_stop(val);
bdb43806 3145 __preempt_count_sub(val);
1da177e4 3146}
bdb43806 3147EXPORT_SYMBOL(preempt_count_sub);
edafe3a5 3148NOKPROBE_SYMBOL(preempt_count_sub);
1da177e4 3149
47252cfb
SR
3150#else
3151static inline void preempt_latency_start(int val) { }
3152static inline void preempt_latency_stop(int val) { }
1da177e4
LT
3153#endif
3154
59ddbcb2
IM
3155static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3156{
3157#ifdef CONFIG_DEBUG_PREEMPT
3158 return p->preempt_disable_ip;
3159#else
3160 return 0;
3161#endif
3162}
3163
1da177e4 3164/*
dd41f596 3165 * Print scheduling while atomic bug:
1da177e4 3166 */
dd41f596 3167static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 3168{
d1c6d149
VN
3169 /* Save this before calling printk(), since that will clobber it */
3170 unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3171
664dfa65
DJ
3172 if (oops_in_progress)
3173 return;
3174
3df0fc5b
PZ
3175 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3176 prev->comm, prev->pid, preempt_count());
838225b4 3177
dd41f596 3178 debug_show_held_locks(prev);
e21f5b15 3179 print_modules();
dd41f596
IM
3180 if (irqs_disabled())
3181 print_irqtrace_events(prev);
d1c6d149
VN
3182 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3183 && in_atomic_preempt_off()) {
8f47b187 3184 pr_err("Preemption disabled at:");
d1c6d149 3185 print_ip_sym(preempt_disable_ip);
8f47b187
TG
3186 pr_cont("\n");
3187 }
748c7201
DBO
3188 if (panic_on_warn)
3189 panic("scheduling while atomic\n");
3190
6135fc1e 3191 dump_stack();
373d4d09 3192 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
dd41f596 3193}
1da177e4 3194
dd41f596
IM
3195/*
3196 * Various schedule()-time debugging checks and statistics:
3197 */
3198static inline void schedule_debug(struct task_struct *prev)
3199{
0d9e2632 3200#ifdef CONFIG_SCHED_STACK_END_CHECK
29d64551
JH
3201 if (task_stack_end_corrupted(prev))
3202 panic("corrupted stack end detected inside scheduler\n");
0d9e2632 3203#endif
b99def8b 3204
1dc0fffc 3205 if (unlikely(in_atomic_preempt_off())) {
dd41f596 3206 __schedule_bug(prev);
1dc0fffc
PZ
3207 preempt_count_set(PREEMPT_DISABLED);
3208 }
b3fbab05 3209 rcu_sleep_check();
dd41f596 3210
1da177e4
LT
3211 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3212
ae92882e 3213 schedstat_inc(this_rq()->sched_count);
dd41f596
IM
3214}
3215
3216/*
3217 * Pick up the highest-prio task:
3218 */
3219static inline struct task_struct *
d8ac8971 3220pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
dd41f596 3221{
49ee5768 3222 const struct sched_class *class;
dd41f596 3223 struct task_struct *p;
1da177e4
LT
3224
3225 /*
0ba87bb2
PZ
3226 * Optimization: we know that if all tasks are in the fair class we can
3227 * call that function directly, but only if the @prev task wasn't of a
3228 * higher scheduling class, because otherwise those loose the
3229 * opportunity to pull in more work from other CPUs.
1da177e4 3230 */
0ba87bb2
PZ
3231 if (likely((prev->sched_class == &idle_sched_class ||
3232 prev->sched_class == &fair_sched_class) &&
3233 rq->nr_running == rq->cfs.h_nr_running)) {
3234
d8ac8971 3235 p = fair_sched_class.pick_next_task(rq, prev, rf);
6ccdc84b
PZ
3236 if (unlikely(p == RETRY_TASK))
3237 goto again;
3238
d1ccc66d 3239 /* Assumes fair_sched_class->next == idle_sched_class */
6ccdc84b 3240 if (unlikely(!p))
d8ac8971 3241 p = idle_sched_class.pick_next_task(rq, prev, rf);
6ccdc84b
PZ
3242
3243 return p;
1da177e4
LT
3244 }
3245
37e117c0 3246again:
34f971f6 3247 for_each_class(class) {
d8ac8971 3248 p = class->pick_next_task(rq, prev, rf);
37e117c0
PZ
3249 if (p) {
3250 if (unlikely(p == RETRY_TASK))
3251 goto again;
dd41f596 3252 return p;
37e117c0 3253 }
dd41f596 3254 }
34f971f6 3255
d1ccc66d
IM
3256 /* The idle class should always have a runnable task: */
3257 BUG();
dd41f596 3258}
1da177e4 3259
dd41f596 3260/*
c259e01a 3261 * __schedule() is the main scheduler function.
edde96ea
PE
3262 *
3263 * The main means of driving the scheduler and thus entering this function are:
3264 *
3265 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3266 *
3267 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3268 * paths. For example, see arch/x86/entry_64.S.
3269 *
3270 * To drive preemption between tasks, the scheduler sets the flag in timer
3271 * interrupt handler scheduler_tick().
3272 *
3273 * 3. Wakeups don't really cause entry into schedule(). They add a
3274 * task to the run-queue and that's it.
3275 *
3276 * Now, if the new task added to the run-queue preempts the current
3277 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3278 * called on the nearest possible occasion:
3279 *
3280 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
3281 *
3282 * - in syscall or exception context, at the next outmost
3283 * preempt_enable(). (this might be as soon as the wake_up()'s
3284 * spin_unlock()!)
3285 *
3286 * - in IRQ context, return from interrupt-handler to
3287 * preemptible context
3288 *
3289 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3290 * then at the next:
3291 *
3292 * - cond_resched() call
3293 * - explicit schedule() call
3294 * - return from syscall or exception to user-space
3295 * - return from interrupt-handler to user-space
bfd9b2b5 3296 *
b30f0e3f 3297 * WARNING: must be called with preemption disabled!
dd41f596 3298 */
499d7955 3299static void __sched notrace __schedule(bool preempt)
dd41f596
IM
3300{
3301 struct task_struct *prev, *next;
67ca7bde 3302 unsigned long *switch_count;
d8ac8971 3303 struct rq_flags rf;
dd41f596 3304 struct rq *rq;
31656519 3305 int cpu;
dd41f596 3306
dd41f596
IM
3307 cpu = smp_processor_id();
3308 rq = cpu_rq(cpu);
dd41f596 3309 prev = rq->curr;
dd41f596 3310
dd41f596 3311 schedule_debug(prev);
1da177e4 3312
31656519 3313 if (sched_feat(HRTICK))
f333fdc9 3314 hrtick_clear(rq);
8f4d37ec 3315
46a5d164 3316 local_irq_disable();
bcbfdd01 3317 rcu_note_context_switch(preempt);
46a5d164 3318
e0acd0a6
ON
3319 /*
3320 * Make sure that signal_pending_state()->signal_pending() below
3321 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3322 * done by the caller to avoid the race with signal_wake_up().
3323 */
8a8c69c3 3324 rq_lock(rq, &rf);
d89e588c 3325 smp_mb__after_spinlock();
1da177e4 3326
d1ccc66d
IM
3327 /* Promote REQ to ACT */
3328 rq->clock_update_flags <<= 1;
bce4dc80 3329 update_rq_clock(rq);
9edfbfed 3330
246d86b5 3331 switch_count = &prev->nivcsw;
fc13aeba 3332 if (!preempt && prev->state) {
21aa9af0 3333 if (unlikely(signal_pending_state(prev->state, prev))) {
1da177e4 3334 prev->state = TASK_RUNNING;
21aa9af0 3335 } else {
bce4dc80 3336 deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
2acca55e
PZ
3337 prev->on_rq = 0;
3338
e33a9bba
TH
3339 if (prev->in_iowait) {
3340 atomic_inc(&rq->nr_iowait);
3341 delayacct_blkio_start();
3342 }
3343
21aa9af0 3344 /*
2acca55e
PZ
3345 * If a worker went to sleep, notify and ask workqueue
3346 * whether it wants to wake up a task to maintain
3347 * concurrency.
21aa9af0
TH
3348 */
3349 if (prev->flags & PF_WQ_WORKER) {
3350 struct task_struct *to_wakeup;
3351
9b7f6597 3352 to_wakeup = wq_worker_sleeping(prev);
21aa9af0 3353 if (to_wakeup)
d8ac8971 3354 try_to_wake_up_local(to_wakeup, &rf);
21aa9af0 3355 }
21aa9af0 3356 }
dd41f596 3357 switch_count = &prev->nvcsw;
1da177e4
LT
3358 }
3359
d8ac8971 3360 next = pick_next_task(rq, prev, &rf);
f26f9aff 3361 clear_tsk_need_resched(prev);
f27dde8d 3362 clear_preempt_need_resched();
1da177e4 3363
1da177e4 3364 if (likely(prev != next)) {
1da177e4
LT
3365 rq->nr_switches++;
3366 rq->curr = next;
22e4ebb9
MD
3367 /*
3368 * The membarrier system call requires each architecture
3369 * to have a full memory barrier after updating
3370 * rq->curr, before returning to user-space. For TSO
3371 * (e.g. x86), the architecture must provide its own
3372 * barrier in switch_mm(). For weakly ordered machines
3373 * for which spin_unlock() acts as a full memory
3374 * barrier, finish_lock_switch() in common code takes
3375 * care of this barrier. For weakly ordered machines for
3376 * which spin_unlock() acts as a RELEASE barrier (only
3377 * arm64 and PowerPC), arm64 has a full barrier in
3378 * switch_to(), and PowerPC has
3379 * smp_mb__after_unlock_lock() before
3380 * finish_lock_switch().
3381 */
1da177e4
LT
3382 ++*switch_count;
3383
c73464b1 3384 trace_sched_switch(preempt, prev, next);
d1ccc66d
IM
3385
3386 /* Also unlocks the rq: */
3387 rq = context_switch(rq, prev, next, &rf);
cbce1a68 3388 } else {
cb42c9a3 3389 rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
8a8c69c3 3390 rq_unlock_irq(rq, &rf);
cbce1a68 3391 }
1da177e4 3392
e3fca9e7 3393 balance_callback(rq);
1da177e4 3394}
c259e01a 3395
9af6528e
PZ
3396void __noreturn do_task_dead(void)
3397{
d1ccc66d 3398 /* Causes final put_task_struct in finish_task_switch(): */
ea19cfd1 3399 set_special_state(TASK_DEAD);
d1ccc66d
IM
3400
3401 /* Tell freezer to ignore us: */
3402 current->flags |= PF_NOFREEZE;
3403
9af6528e
PZ
3404 __schedule(false);
3405 BUG();
d1ccc66d
IM
3406
3407 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
9af6528e 3408 for (;;)
d1ccc66d 3409 cpu_relax();
9af6528e
PZ
3410}
3411
9c40cef2
TG
3412static inline void sched_submit_work(struct task_struct *tsk)
3413{
3c7d5184 3414 if (!tsk->state || tsk_is_pi_blocked(tsk))
9c40cef2
TG
3415 return;
3416 /*
3417 * If we are going to sleep and we have plugged IO queued,
3418 * make sure to submit it to avoid deadlocks.
3419 */
3420 if (blk_needs_flush_plug(tsk))
3421 blk_schedule_flush_plug(tsk);
3422}
3423
722a9f92 3424asmlinkage __visible void __sched schedule(void)
c259e01a 3425{
9c40cef2
TG
3426 struct task_struct *tsk = current;
3427
3428 sched_submit_work(tsk);
bfd9b2b5 3429 do {
b30f0e3f 3430 preempt_disable();
fc13aeba 3431 __schedule(false);
b30f0e3f 3432 sched_preempt_enable_no_resched();
bfd9b2b5 3433 } while (need_resched());
c259e01a 3434}
1da177e4
LT
3435EXPORT_SYMBOL(schedule);
3436
8663effb
SRV
3437/*
3438 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3439 * state (have scheduled out non-voluntarily) by making sure that all
3440 * tasks have either left the run queue or have gone into user space.
3441 * As idle tasks do not do either, they must not ever be preempted
3442 * (schedule out non-voluntarily).
3443 *
3444 * schedule_idle() is similar to schedule_preempt_disable() except that it
3445 * never enables preemption because it does not call sched_submit_work().
3446 */
3447void __sched schedule_idle(void)
3448{
3449 /*
3450 * As this skips calling sched_submit_work(), which the idle task does
3451 * regardless because that function is a nop when the task is in a
3452 * TASK_RUNNING state, make sure this isn't used someplace that the
3453 * current task can be in any other state. Note, idle is always in the
3454 * TASK_RUNNING state.
3455 */
3456 WARN_ON_ONCE(current->state);
3457 do {
3458 __schedule(false);
3459 } while (need_resched());
3460}
3461
91d1aa43 3462#ifdef CONFIG_CONTEXT_TRACKING
722a9f92 3463asmlinkage __visible void __sched schedule_user(void)
20ab65e3
FW
3464{
3465 /*
3466 * If we come here after a random call to set_need_resched(),
3467 * or we have been woken up remotely but the IPI has not yet arrived,
3468 * we haven't yet exited the RCU idle mode. Do it here manually until
3469 * we find a better solution.
7cc78f8f
AL
3470 *
3471 * NB: There are buggy callers of this function. Ideally we
c467ea76 3472 * should warn if prev_state != CONTEXT_USER, but that will trigger
7cc78f8f 3473 * too frequently to make sense yet.
20ab65e3 3474 */
7cc78f8f 3475 enum ctx_state prev_state = exception_enter();
20ab65e3 3476 schedule();
7cc78f8f 3477 exception_exit(prev_state);
20ab65e3
FW
3478}
3479#endif
3480
c5491ea7
TG
3481/**
3482 * schedule_preempt_disabled - called with preemption disabled
3483 *
3484 * Returns with preemption disabled. Note: preempt_count must be 1
3485 */
3486void __sched schedule_preempt_disabled(void)
3487{
ba74c144 3488 sched_preempt_enable_no_resched();
c5491ea7
TG
3489 schedule();
3490 preempt_disable();
3491}
3492
06b1f808 3493static void __sched notrace preempt_schedule_common(void)
a18b5d01
FW
3494{
3495 do {
47252cfb
SR
3496 /*
3497 * Because the function tracer can trace preempt_count_sub()
3498 * and it also uses preempt_enable/disable_notrace(), if
3499 * NEED_RESCHED is set, the preempt_enable_notrace() called
3500 * by the function tracer will call this function again and
3501 * cause infinite recursion.
3502 *
3503 * Preemption must be disabled here before the function
3504 * tracer can trace. Break up preempt_disable() into two
3505 * calls. One to disable preemption without fear of being
3506 * traced. The other to still record the preemption latency,
3507 * which can also be traced by the function tracer.
3508 */
499d7955 3509 preempt_disable_notrace();
47252cfb 3510 preempt_latency_start(1);
fc13aeba 3511 __schedule(true);
47252cfb 3512 preempt_latency_stop(1);
499d7955 3513 preempt_enable_no_resched_notrace();
a18b5d01
FW
3514
3515 /*
3516 * Check again in case we missed a preemption opportunity
3517 * between schedule and now.
3518 */
a18b5d01
FW
3519 } while (need_resched());
3520}
3521
1da177e4
LT
3522#ifdef CONFIG_PREEMPT
3523/*
2ed6e34f 3524 * this is the entry point to schedule() from in-kernel preemption
41a2d6cf 3525 * off of preempt_enable. Kernel preemptions off return from interrupt
1da177e4
LT
3526 * occur there and call schedule directly.
3527 */
722a9f92 3528asmlinkage __visible void __sched notrace preempt_schedule(void)
1da177e4 3529{
1da177e4
LT
3530 /*
3531 * If there is a non-zero preempt_count or interrupts are disabled,
41a2d6cf 3532 * we do not want to preempt the current task. Just return..
1da177e4 3533 */
fbb00b56 3534 if (likely(!preemptible()))
1da177e4
LT
3535 return;
3536
a18b5d01 3537 preempt_schedule_common();
1da177e4 3538}
376e2424 3539NOKPROBE_SYMBOL(preempt_schedule);
1da177e4 3540EXPORT_SYMBOL(preempt_schedule);
009f60e2 3541
009f60e2 3542/**
4eaca0a8 3543 * preempt_schedule_notrace - preempt_schedule called by tracing
009f60e2
ON
3544 *
3545 * The tracing infrastructure uses preempt_enable_notrace to prevent
3546 * recursion and tracing preempt enabling caused by the tracing
3547 * infrastructure itself. But as tracing can happen in areas coming
3548 * from userspace or just about to enter userspace, a preempt enable
3549 * can occur before user_exit() is called. This will cause the scheduler
3550 * to be called when the system is still in usermode.
3551 *
3552 * To prevent this, the preempt_enable_notrace will use this function
3553 * instead of preempt_schedule() to exit user context if needed before
3554 * calling the scheduler.
3555 */
4eaca0a8 3556asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
009f60e2
ON
3557{
3558 enum ctx_state prev_ctx;
3559
3560 if (likely(!preemptible()))
3561 return;
3562
3563 do {
47252cfb
SR
3564 /*
3565 * Because the function tracer can trace preempt_count_sub()
3566 * and it also uses preempt_enable/disable_notrace(), if
3567 * NEED_RESCHED is set, the preempt_enable_notrace() called
3568 * by the function tracer will call this function again and
3569 * cause infinite recursion.
3570 *
3571 * Preemption must be disabled here before the function
3572 * tracer can trace. Break up preempt_disable() into two
3573 * calls. One to disable preemption without fear of being
3574 * traced. The other to still record the preemption latency,
3575 * which can also be traced by the function tracer.
3576 */
3d8f74dd 3577 preempt_disable_notrace();
47252cfb 3578 preempt_latency_start(1);
009f60e2
ON
3579 /*
3580 * Needs preempt disabled in case user_exit() is traced
3581 * and the tracer calls preempt_enable_notrace() causing
3582 * an infinite recursion.
3583 */
3584 prev_ctx = exception_enter();
fc13aeba 3585 __schedule(true);
009f60e2
ON
3586 exception_exit(prev_ctx);
3587
47252cfb 3588 preempt_latency_stop(1);
3d8f74dd 3589 preempt_enable_no_resched_notrace();
009f60e2
ON
3590 } while (need_resched());
3591}
4eaca0a8 3592EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
009f60e2 3593
32e475d7 3594#endif /* CONFIG_PREEMPT */
1da177e4
LT
3595
3596/*
2ed6e34f 3597 * this is the entry point to schedule() from kernel preemption
1da177e4
LT
3598 * off of irq context.
3599 * Note, that this is called and return with irqs disabled. This will
3600 * protect us against recursive calling from irq.
3601 */
722a9f92 3602asmlinkage __visible void __sched preempt_schedule_irq(void)
1da177e4 3603{
b22366cd 3604 enum ctx_state prev_state;
6478d880 3605
2ed6e34f 3606 /* Catch callers which need to be fixed */
f27dde8d 3607 BUG_ON(preempt_count() || !irqs_disabled());
1da177e4 3608
b22366cd
FW
3609 prev_state = exception_enter();
3610
3a5c359a 3611 do {
3d8f74dd 3612 preempt_disable();
3a5c359a 3613 local_irq_enable();
fc13aeba 3614 __schedule(true);
3a5c359a 3615 local_irq_disable();
3d8f74dd 3616 sched_preempt_enable_no_resched();
5ed0cec0 3617 } while (need_resched());
b22366cd
FW
3618
3619 exception_exit(prev_state);
1da177e4
LT
3620}
3621
ac6424b9 3622int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
95cdf3b7 3623 void *key)
1da177e4 3624{
63859d4f 3625 return try_to_wake_up(curr->private, mode, wake_flags);
1da177e4 3626}
1da177e4
LT
3627EXPORT_SYMBOL(default_wake_function);
3628
b29739f9
IM
3629#ifdef CONFIG_RT_MUTEXES
3630
acd58620
PZ
3631static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
3632{
3633 if (pi_task)
3634 prio = min(prio, pi_task->prio);
3635
3636 return prio;
3637}
3638
3639static inline int rt_effective_prio(struct task_struct *p, int prio)
3640{
3641 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3642
3643 return __rt_effective_prio(pi_task, prio);
3644}
3645
b29739f9
IM
3646/*
3647 * rt_mutex_setprio - set the current priority of a task
acd58620
PZ
3648 * @p: task to boost
3649 * @pi_task: donor task
b29739f9
IM
3650 *
3651 * This function changes the 'effective' priority of a task. It does
3652 * not touch ->normal_prio like __setscheduler().
3653 *
c365c292
TG
3654 * Used by the rt_mutex code to implement priority inheritance
3655 * logic. Call site only calls if the priority of the task changed.
b29739f9 3656 */
acd58620 3657void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
b29739f9 3658{
acd58620 3659 int prio, oldprio, queued, running, queue_flag =
7a57f32a 3660 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
83ab0aa0 3661 const struct sched_class *prev_class;
eb580751
PZ
3662 struct rq_flags rf;
3663 struct rq *rq;
b29739f9 3664
acd58620
PZ
3665 /* XXX used to be waiter->prio, not waiter->task->prio */
3666 prio = __rt_effective_prio(pi_task, p->normal_prio);
3667
3668 /*
3669 * If nothing changed; bail early.
3670 */
3671 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
3672 return;
b29739f9 3673
eb580751 3674 rq = __task_rq_lock(p, &rf);
80f5c1b8 3675 update_rq_clock(rq);
acd58620
PZ
3676 /*
3677 * Set under pi_lock && rq->lock, such that the value can be used under
3678 * either lock.
3679 *
3680 * Note that there is loads of tricky to make this pointer cache work
3681 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3682 * ensure a task is de-boosted (pi_task is set to NULL) before the
3683 * task is allowed to run again (and can exit). This ensures the pointer
3684 * points to a blocked task -- which guaratees the task is present.
3685 */
3686 p->pi_top_task = pi_task;
3687
3688 /*
3689 * For FIFO/RR we only need to set prio, if that matches we're done.
3690 */
3691 if (prio == p->prio && !dl_prio(prio))
3692 goto out_unlock;
b29739f9 3693
1c4dd99b
TG
3694 /*
3695 * Idle task boosting is a nono in general. There is one
3696 * exception, when PREEMPT_RT and NOHZ is active:
3697 *
3698 * The idle task calls get_next_timer_interrupt() and holds
3699 * the timer wheel base->lock on the CPU and another CPU wants
3700 * to access the timer (probably to cancel it). We can safely
3701 * ignore the boosting request, as the idle CPU runs this code
3702 * with interrupts disabled and will complete the lock
3703 * protected section without being interrupted. So there is no
3704 * real need to boost.
3705 */
3706 if (unlikely(p == rq->idle)) {
3707 WARN_ON(p != rq->curr);
3708 WARN_ON(p->pi_blocked_on);
3709 goto out_unlock;
3710 }
3711
b91473ff 3712 trace_sched_pi_setprio(p, pi_task);
d5f9f942 3713 oldprio = p->prio;
ff77e468
PZ
3714
3715 if (oldprio == prio)
3716 queue_flag &= ~DEQUEUE_MOVE;
3717
83ab0aa0 3718 prev_class = p->sched_class;
da0c1e65 3719 queued = task_on_rq_queued(p);
051a1d1a 3720 running = task_current(rq, p);
da0c1e65 3721 if (queued)
ff77e468 3722 dequeue_task(rq, p, queue_flag);
0e1f3483 3723 if (running)
f3cd1c4e 3724 put_prev_task(rq, p);
dd41f596 3725
2d3d891d
DF
3726 /*
3727 * Boosting condition are:
3728 * 1. -rt task is running and holds mutex A
3729 * --> -dl task blocks on mutex A
3730 *
3731 * 2. -dl task is running and holds mutex A
3732 * --> -dl task blocks on mutex A and could preempt the
3733 * running task
3734 */
3735 if (dl_prio(prio)) {
466af29b
ON
3736 if (!dl_prio(p->normal_prio) ||
3737 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
2d3d891d 3738 p->dl.dl_boosted = 1;
ff77e468 3739 queue_flag |= ENQUEUE_REPLENISH;
2d3d891d
DF
3740 } else
3741 p->dl.dl_boosted = 0;
aab03e05 3742 p->sched_class = &dl_sched_class;
2d3d891d
DF
3743 } else if (rt_prio(prio)) {
3744 if (dl_prio(oldprio))
3745 p->dl.dl_boosted = 0;
3746 if (oldprio < prio)
ff77e468 3747 queue_flag |= ENQUEUE_HEAD;
dd41f596 3748 p->sched_class = &rt_sched_class;
2d3d891d
DF
3749 } else {
3750 if (dl_prio(oldprio))
3751 p->dl.dl_boosted = 0;
746db944
BS
3752 if (rt_prio(oldprio))
3753 p->rt.timeout = 0;
dd41f596 3754 p->sched_class = &fair_sched_class;
2d3d891d 3755 }
dd41f596 3756
b29739f9
IM
3757 p->prio = prio;
3758
da0c1e65 3759 if (queued)
ff77e468 3760 enqueue_task(rq, p, queue_flag);
a399d233 3761 if (running)
b2bf6c31 3762 set_curr_task(rq, p);
cb469845 3763
da7a735e 3764 check_class_changed(rq, p, prev_class, oldprio);
1c4dd99b 3765out_unlock:
d1ccc66d
IM
3766 /* Avoid rq from going away on us: */
3767 preempt_disable();
eb580751 3768 __task_rq_unlock(rq, &rf);
4c9a4bc8
PZ
3769
3770 balance_callback(rq);
3771 preempt_enable();
b29739f9 3772}
acd58620
PZ
3773#else
3774static inline int rt_effective_prio(struct task_struct *p, int prio)
3775{
3776 return prio;
3777}
b29739f9 3778#endif
d50dde5a 3779
36c8b586 3780void set_user_nice(struct task_struct *p, long nice)
1da177e4 3781{
49bd21ef
PZ
3782 bool queued, running;
3783 int old_prio, delta;
eb580751 3784 struct rq_flags rf;
70b97a7f 3785 struct rq *rq;
1da177e4 3786
75e45d51 3787 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
1da177e4
LT
3788 return;
3789 /*
3790 * We have to be careful, if called from sys_setpriority(),
3791 * the task might be in the middle of scheduling on another CPU.
3792 */
eb580751 3793 rq = task_rq_lock(p, &rf);
2fb8d367
PZ
3794 update_rq_clock(rq);
3795
1da177e4
LT
3796 /*
3797 * The RT priorities are set via sched_setscheduler(), but we still
3798 * allow the 'normal' nice value to be set - but as expected
3799 * it wont have any effect on scheduling until the task is
aab03e05 3800 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
1da177e4 3801 */
aab03e05 3802 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
1da177e4
LT
3803 p->static_prio = NICE_TO_PRIO(nice);
3804 goto out_unlock;
3805 }
da0c1e65 3806 queued = task_on_rq_queued(p);
49bd21ef 3807 running = task_current(rq, p);
da0c1e65 3808 if (queued)
7a57f32a 3809 dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
49bd21ef
PZ
3810 if (running)
3811 put_prev_task(rq, p);
1da177e4 3812
1da177e4 3813 p->static_prio = NICE_TO_PRIO(nice);
9059393e 3814 set_load_weight(p, true);
b29739f9
IM
3815 old_prio = p->prio;
3816 p->prio = effective_prio(p);
3817 delta = p->prio - old_prio;
1da177e4 3818
da0c1e65 3819 if (queued) {
7134b3e9 3820 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1da177e4 3821 /*
d5f9f942
AM
3822 * If the task increased its priority or is running and
3823 * lowered its priority, then reschedule its CPU:
1da177e4 3824 */
d5f9f942 3825 if (delta < 0 || (delta > 0 && task_running(rq, p)))
8875125e 3826 resched_curr(rq);
1da177e4 3827 }
49bd21ef
PZ
3828 if (running)
3829 set_curr_task(rq, p);
1da177e4 3830out_unlock:
eb580751 3831 task_rq_unlock(rq, p, &rf);
1da177e4 3832}
1da177e4
LT
3833EXPORT_SYMBOL(set_user_nice);
3834
e43379f1
MM
3835/*
3836 * can_nice - check if a task can reduce its nice value
3837 * @p: task
3838 * @nice: nice value
3839 */
36c8b586 3840int can_nice(const struct task_struct *p, const int nice)
e43379f1 3841{
d1ccc66d 3842 /* Convert nice value [19,-20] to rlimit style value [1,40]: */
7aa2c016 3843 int nice_rlim = nice_to_rlimit(nice);
48f24c4d 3844
78d7d407 3845 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
e43379f1
MM
3846 capable(CAP_SYS_NICE));
3847}
3848
1da177e4
LT
3849#ifdef __ARCH_WANT_SYS_NICE
3850
3851/*
3852 * sys_nice - change the priority of the current process.
3853 * @increment: priority increment
3854 *
3855 * sys_setpriority is a more generic, but much slower function that
3856 * does similar things.
3857 */
5add95d4 3858SYSCALL_DEFINE1(nice, int, increment)
1da177e4 3859{
48f24c4d 3860 long nice, retval;
1da177e4
LT
3861
3862 /*
3863 * Setpriority might change our priority at the same moment.
3864 * We don't have to worry. Conceptually one call occurs first
3865 * and we have a single winner.
3866 */
a9467fa3 3867 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
d0ea0268 3868 nice = task_nice(current) + increment;
1da177e4 3869
a9467fa3 3870 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
e43379f1
MM
3871 if (increment < 0 && !can_nice(current, nice))
3872 return -EPERM;
3873
1da177e4
LT
3874 retval = security_task_setnice(current, nice);
3875 if (retval)
3876 return retval;
3877
3878 set_user_nice(current, nice);
3879 return 0;
3880}
3881
3882#endif
3883
3884/**
3885 * task_prio - return the priority value of a given task.
3886 * @p: the task in question.
3887 *
e69f6186 3888 * Return: The priority value as seen by users in /proc.
1da177e4
LT
3889 * RT tasks are offset by -200. Normal tasks are centered
3890 * around 0, value goes from -16 to +15.
3891 */
36c8b586 3892int task_prio(const struct task_struct *p)
1da177e4
LT
3893{
3894 return p->prio - MAX_RT_PRIO;
3895}
3896
1da177e4 3897/**
d1ccc66d 3898 * idle_cpu - is a given CPU idle currently?
1da177e4 3899 * @cpu: the processor in question.
e69f6186
YB
3900 *
3901 * Return: 1 if the CPU is currently idle. 0 otherwise.
1da177e4
LT
3902 */
3903int idle_cpu(int cpu)
3904{
908a3283
TG
3905 struct rq *rq = cpu_rq(cpu);
3906
3907 if (rq->curr != rq->idle)
3908 return 0;
3909
3910 if (rq->nr_running)
3911 return 0;
3912
3913#ifdef CONFIG_SMP
3914 if (!llist_empty(&rq->wake_list))
3915 return 0;
3916#endif
3917
3918 return 1;
1da177e4
LT
3919}
3920
1da177e4 3921/**
d1ccc66d 3922 * idle_task - return the idle task for a given CPU.
1da177e4 3923 * @cpu: the processor in question.
e69f6186 3924 *
d1ccc66d 3925 * Return: The idle task for the CPU @cpu.
1da177e4 3926 */
36c8b586 3927struct task_struct *idle_task(int cpu)
1da177e4
LT
3928{
3929 return cpu_rq(cpu)->idle;
3930}
3931
3932/**
3933 * find_process_by_pid - find a process with a matching PID value.
3934 * @pid: the pid in question.
e69f6186
YB
3935 *
3936 * The task of @pid, if found. %NULL otherwise.
1da177e4 3937 */
a9957449 3938static struct task_struct *find_process_by_pid(pid_t pid)
1da177e4 3939{
228ebcbe 3940 return pid ? find_task_by_vpid(pid) : current;
1da177e4
LT
3941}
3942
c13db6b1
SR
3943/*
3944 * sched_setparam() passes in -1 for its policy, to let the functions
3945 * it calls know not to change it.
3946 */
3947#define SETPARAM_POLICY -1
3948
c365c292
TG
3949static void __setscheduler_params(struct task_struct *p,
3950 const struct sched_attr *attr)
1da177e4 3951{
d50dde5a
DF
3952 int policy = attr->sched_policy;
3953
c13db6b1 3954 if (policy == SETPARAM_POLICY)
39fd8fd2
PZ
3955 policy = p->policy;
3956
1da177e4 3957 p->policy = policy;
d50dde5a 3958
aab03e05
DF
3959 if (dl_policy(policy))
3960 __setparam_dl(p, attr);
39fd8fd2 3961 else if (fair_policy(policy))
d50dde5a
DF
3962 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
3963
39fd8fd2
PZ
3964 /*
3965 * __sched_setscheduler() ensures attr->sched_priority == 0 when
3966 * !rt_policy. Always setting this ensures that things like
3967 * getparam()/getattr() don't report silly values for !rt tasks.
3968 */
3969 p->rt_priority = attr->sched_priority;
383afd09 3970 p->normal_prio = normal_prio(p);
9059393e 3971 set_load_weight(p, true);
c365c292 3972}
39fd8fd2 3973
c365c292
TG
3974/* Actually do priority change: must hold pi & rq lock. */
3975static void __setscheduler(struct rq *rq, struct task_struct *p,
0782e63b 3976 const struct sched_attr *attr, bool keep_boost)
c365c292
TG
3977{
3978 __setscheduler_params(p, attr);
d50dde5a 3979
383afd09 3980 /*
0782e63b
TG
3981 * Keep a potential priority boosting if called from
3982 * sched_setscheduler().
383afd09 3983 */
acd58620 3984 p->prio = normal_prio(p);
0782e63b 3985 if (keep_boost)
acd58620 3986 p->prio = rt_effective_prio(p, p->prio);
383afd09 3987
aab03e05
DF
3988 if (dl_prio(p->prio))
3989 p->sched_class = &dl_sched_class;
3990 else if (rt_prio(p->prio))
ffd44db5
PZ
3991 p->sched_class = &rt_sched_class;
3992 else
3993 p->sched_class = &fair_sched_class;
1da177e4 3994}
aab03e05 3995
c69e8d9c 3996/*
d1ccc66d 3997 * Check the target process has a UID that matches the current process's:
c69e8d9c
DH
3998 */
3999static bool check_same_owner(struct task_struct *p)
4000{
4001 const struct cred *cred = current_cred(), *pcred;
4002 bool match;
4003
4004 rcu_read_lock();
4005 pcred = __task_cred(p);
9c806aa0
EB
4006 match = (uid_eq(cred->euid, pcred->euid) ||
4007 uid_eq(cred->euid, pcred->uid));
c69e8d9c
DH
4008 rcu_read_unlock();
4009 return match;
4010}
4011
d50dde5a
DF
4012static int __sched_setscheduler(struct task_struct *p,
4013 const struct sched_attr *attr,
dbc7f069 4014 bool user, bool pi)
1da177e4 4015{
383afd09
SR
4016 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4017 MAX_RT_PRIO - 1 - attr->sched_priority;
da0c1e65 4018 int retval, oldprio, oldpolicy = -1, queued, running;
0782e63b 4019 int new_effective_prio, policy = attr->sched_policy;
83ab0aa0 4020 const struct sched_class *prev_class;
eb580751 4021 struct rq_flags rf;
ca94c442 4022 int reset_on_fork;
7a57f32a 4023 int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
eb580751 4024 struct rq *rq;
1da177e4 4025
896bbb25
SRV
4026 /* The pi code expects interrupts enabled */
4027 BUG_ON(pi && in_interrupt());
1da177e4 4028recheck:
d1ccc66d 4029 /* Double check policy once rq lock held: */
ca94c442
LP
4030 if (policy < 0) {
4031 reset_on_fork = p->sched_reset_on_fork;
1da177e4 4032 policy = oldpolicy = p->policy;
ca94c442 4033 } else {
7479f3c9 4034 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
ca94c442 4035
20f9cd2a 4036 if (!valid_policy(policy))
ca94c442
LP
4037 return -EINVAL;
4038 }
4039
2d4283e9
LA
4040 if (attr->sched_flags &
4041 ~(SCHED_FLAG_RESET_ON_FORK | SCHED_FLAG_RECLAIM))
7479f3c9
PZ
4042 return -EINVAL;
4043
1da177e4
LT
4044 /*
4045 * Valid priorities for SCHED_FIFO and SCHED_RR are
dd41f596
IM
4046 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4047 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4 4048 */
0bb040a4 4049 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
d50dde5a 4050 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
1da177e4 4051 return -EINVAL;
aab03e05
DF
4052 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4053 (rt_policy(policy) != (attr->sched_priority != 0)))
1da177e4
LT
4054 return -EINVAL;
4055
37e4ab3f
OC
4056 /*
4057 * Allow unprivileged RT tasks to decrease priority:
4058 */
961ccddd 4059 if (user && !capable(CAP_SYS_NICE)) {
d50dde5a 4060 if (fair_policy(policy)) {
d0ea0268 4061 if (attr->sched_nice < task_nice(p) &&
eaad4513 4062 !can_nice(p, attr->sched_nice))
d50dde5a
DF
4063 return -EPERM;
4064 }
4065
e05606d3 4066 if (rt_policy(policy)) {
a44702e8
ON
4067 unsigned long rlim_rtprio =
4068 task_rlimit(p, RLIMIT_RTPRIO);
8dc3e909 4069
d1ccc66d 4070 /* Can't set/change the rt policy: */
8dc3e909
ON
4071 if (policy != p->policy && !rlim_rtprio)
4072 return -EPERM;
4073
d1ccc66d 4074 /* Can't increase priority: */
d50dde5a
DF
4075 if (attr->sched_priority > p->rt_priority &&
4076 attr->sched_priority > rlim_rtprio)
8dc3e909
ON
4077 return -EPERM;
4078 }
c02aa73b 4079
d44753b8
JL
4080 /*
4081 * Can't set/change SCHED_DEADLINE policy at all for now
4082 * (safest behavior); in the future we would like to allow
4083 * unprivileged DL tasks to increase their relative deadline
4084 * or reduce their runtime (both ways reducing utilization)
4085 */
4086 if (dl_policy(policy))
4087 return -EPERM;
4088
dd41f596 4089 /*
c02aa73b
DH
4090 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4091 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
dd41f596 4092 */
20f9cd2a 4093 if (idle_policy(p->policy) && !idle_policy(policy)) {
d0ea0268 4094 if (!can_nice(p, task_nice(p)))
c02aa73b
DH
4095 return -EPERM;
4096 }
5fe1d75f 4097
d1ccc66d 4098 /* Can't change other user's priorities: */
c69e8d9c 4099 if (!check_same_owner(p))
37e4ab3f 4100 return -EPERM;
ca94c442 4101
d1ccc66d 4102 /* Normal users shall not reset the sched_reset_on_fork flag: */
ca94c442
LP
4103 if (p->sched_reset_on_fork && !reset_on_fork)
4104 return -EPERM;
37e4ab3f 4105 }
1da177e4 4106
725aad24 4107 if (user) {
b0ae1981 4108 retval = security_task_setscheduler(p);
725aad24
JF
4109 if (retval)
4110 return retval;
4111 }
4112
b29739f9 4113 /*
d1ccc66d 4114 * Make sure no PI-waiters arrive (or leave) while we are
b29739f9 4115 * changing the priority of the task:
0122ec5b 4116 *
25985edc 4117 * To be able to change p->policy safely, the appropriate
1da177e4
LT
4118 * runqueue lock must be held.
4119 */
eb580751 4120 rq = task_rq_lock(p, &rf);
80f5c1b8 4121 update_rq_clock(rq);
dc61b1d6 4122
34f971f6 4123 /*
d1ccc66d 4124 * Changing the policy of the stop threads its a very bad idea:
34f971f6
PZ
4125 */
4126 if (p == rq->stop) {
eb580751 4127 task_rq_unlock(rq, p, &rf);
34f971f6
PZ
4128 return -EINVAL;
4129 }
4130
a51e9198 4131 /*
d6b1e911
TG
4132 * If not changing anything there's no need to proceed further,
4133 * but store a possible modification of reset_on_fork.
a51e9198 4134 */
d50dde5a 4135 if (unlikely(policy == p->policy)) {
d0ea0268 4136 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
d50dde5a
DF
4137 goto change;
4138 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4139 goto change;
75381608 4140 if (dl_policy(policy) && dl_param_changed(p, attr))
aab03e05 4141 goto change;
d50dde5a 4142
d6b1e911 4143 p->sched_reset_on_fork = reset_on_fork;
eb580751 4144 task_rq_unlock(rq, p, &rf);
a51e9198
DF
4145 return 0;
4146 }
d50dde5a 4147change:
a51e9198 4148
dc61b1d6 4149 if (user) {
332ac17e 4150#ifdef CONFIG_RT_GROUP_SCHED
dc61b1d6
PZ
4151 /*
4152 * Do not allow realtime tasks into groups that have no runtime
4153 * assigned.
4154 */
4155 if (rt_bandwidth_enabled() && rt_policy(policy) &&
f4493771
MG
4156 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4157 !task_group_is_autogroup(task_group(p))) {
eb580751 4158 task_rq_unlock(rq, p, &rf);
dc61b1d6
PZ
4159 return -EPERM;
4160 }
dc61b1d6 4161#endif
332ac17e
DF
4162#ifdef CONFIG_SMP
4163 if (dl_bandwidth_enabled() && dl_policy(policy)) {
4164 cpumask_t *span = rq->rd->span;
332ac17e
DF
4165
4166 /*
4167 * Don't allow tasks with an affinity mask smaller than
4168 * the entire root_domain to become SCHED_DEADLINE. We
4169 * will also fail if there's no bandwidth available.
4170 */
e4099a5e
PZ
4171 if (!cpumask_subset(span, &p->cpus_allowed) ||
4172 rq->rd->dl_bw.bw == 0) {
eb580751 4173 task_rq_unlock(rq, p, &rf);
332ac17e
DF
4174 return -EPERM;
4175 }
4176 }
4177#endif
4178 }
dc61b1d6 4179
d1ccc66d 4180 /* Re-check policy now with rq lock held: */
1da177e4
LT
4181 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4182 policy = oldpolicy = -1;
eb580751 4183 task_rq_unlock(rq, p, &rf);
1da177e4
LT
4184 goto recheck;
4185 }
332ac17e
DF
4186
4187 /*
4188 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4189 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4190 * is available.
4191 */
06a76fe0 4192 if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
eb580751 4193 task_rq_unlock(rq, p, &rf);
332ac17e
DF
4194 return -EBUSY;
4195 }
4196
c365c292
TG
4197 p->sched_reset_on_fork = reset_on_fork;
4198 oldprio = p->prio;
4199
dbc7f069
PZ
4200 if (pi) {
4201 /*
4202 * Take priority boosted tasks into account. If the new
4203 * effective priority is unchanged, we just store the new
4204 * normal parameters and do not touch the scheduler class and
4205 * the runqueue. This will be done when the task deboost
4206 * itself.
4207 */
acd58620 4208 new_effective_prio = rt_effective_prio(p, newprio);
ff77e468
PZ
4209 if (new_effective_prio == oldprio)
4210 queue_flags &= ~DEQUEUE_MOVE;
c365c292
TG
4211 }
4212
da0c1e65 4213 queued = task_on_rq_queued(p);
051a1d1a 4214 running = task_current(rq, p);
da0c1e65 4215 if (queued)
ff77e468 4216 dequeue_task(rq, p, queue_flags);
0e1f3483 4217 if (running)
f3cd1c4e 4218 put_prev_task(rq, p);
f6b53205 4219
83ab0aa0 4220 prev_class = p->sched_class;
dbc7f069 4221 __setscheduler(rq, p, attr, pi);
f6b53205 4222
da0c1e65 4223 if (queued) {
81a44c54
TG
4224 /*
4225 * We enqueue to tail when the priority of a task is
4226 * increased (user space view).
4227 */
ff77e468
PZ
4228 if (oldprio < p->prio)
4229 queue_flags |= ENQUEUE_HEAD;
1de64443 4230
ff77e468 4231 enqueue_task(rq, p, queue_flags);
81a44c54 4232 }
a399d233 4233 if (running)
b2bf6c31 4234 set_curr_task(rq, p);
cb469845 4235
da7a735e 4236 check_class_changed(rq, p, prev_class, oldprio);
d1ccc66d
IM
4237
4238 /* Avoid rq from going away on us: */
4239 preempt_disable();
eb580751 4240 task_rq_unlock(rq, p, &rf);
b29739f9 4241
dbc7f069
PZ
4242 if (pi)
4243 rt_mutex_adjust_pi(p);
95e02ca9 4244
d1ccc66d 4245 /* Run balance callbacks after we've adjusted the PI chain: */
4c9a4bc8
PZ
4246 balance_callback(rq);
4247 preempt_enable();
95e02ca9 4248
1da177e4
LT
4249 return 0;
4250}
961ccddd 4251
7479f3c9
PZ
4252static int _sched_setscheduler(struct task_struct *p, int policy,
4253 const struct sched_param *param, bool check)
4254{
4255 struct sched_attr attr = {
4256 .sched_policy = policy,
4257 .sched_priority = param->sched_priority,
4258 .sched_nice = PRIO_TO_NICE(p->static_prio),
4259 };
4260
c13db6b1
SR
4261 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4262 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
7479f3c9
PZ
4263 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4264 policy &= ~SCHED_RESET_ON_FORK;
4265 attr.sched_policy = policy;
4266 }
4267
dbc7f069 4268 return __sched_setscheduler(p, &attr, check, true);
7479f3c9 4269}
961ccddd
RR
4270/**
4271 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4272 * @p: the task in question.
4273 * @policy: new policy.
4274 * @param: structure containing the new RT priority.
4275 *
e69f6186
YB
4276 * Return: 0 on success. An error code otherwise.
4277 *
961ccddd
RR
4278 * NOTE that the task may be already dead.
4279 */
4280int sched_setscheduler(struct task_struct *p, int policy,
fe7de49f 4281 const struct sched_param *param)
961ccddd 4282{
7479f3c9 4283 return _sched_setscheduler(p, policy, param, true);
961ccddd 4284}
1da177e4
LT
4285EXPORT_SYMBOL_GPL(sched_setscheduler);
4286
d50dde5a
DF
4287int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4288{
dbc7f069 4289 return __sched_setscheduler(p, attr, true, true);
d50dde5a
DF
4290}
4291EXPORT_SYMBOL_GPL(sched_setattr);
4292
961ccddd
RR
4293/**
4294 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4295 * @p: the task in question.
4296 * @policy: new policy.
4297 * @param: structure containing the new RT priority.
4298 *
4299 * Just like sched_setscheduler, only don't bother checking if the
4300 * current context has permission. For example, this is needed in
4301 * stop_machine(): we create temporary high priority worker threads,
4302 * but our caller might not have that capability.
e69f6186
YB
4303 *
4304 * Return: 0 on success. An error code otherwise.
961ccddd
RR
4305 */
4306int sched_setscheduler_nocheck(struct task_struct *p, int policy,
fe7de49f 4307 const struct sched_param *param)
961ccddd 4308{
7479f3c9 4309 return _sched_setscheduler(p, policy, param, false);
961ccddd 4310}
84778472 4311EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
961ccddd 4312
95cdf3b7
IM
4313static int
4314do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 4315{
1da177e4
LT
4316 struct sched_param lparam;
4317 struct task_struct *p;
36c8b586 4318 int retval;
1da177e4
LT
4319
4320 if (!param || pid < 0)
4321 return -EINVAL;
4322 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4323 return -EFAULT;
5fe1d75f
ON
4324
4325 rcu_read_lock();
4326 retval = -ESRCH;
1da177e4 4327 p = find_process_by_pid(pid);
5fe1d75f
ON
4328 if (p != NULL)
4329 retval = sched_setscheduler(p, policy, &lparam);
4330 rcu_read_unlock();
36c8b586 4331
1da177e4
LT
4332 return retval;
4333}
4334
d50dde5a
DF
4335/*
4336 * Mimics kernel/events/core.c perf_copy_attr().
4337 */
d1ccc66d 4338static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
d50dde5a
DF
4339{
4340 u32 size;
4341 int ret;
4342
4343 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4344 return -EFAULT;
4345
d1ccc66d 4346 /* Zero the full structure, so that a short copy will be nice: */
d50dde5a
DF
4347 memset(attr, 0, sizeof(*attr));
4348
4349 ret = get_user(size, &uattr->size);
4350 if (ret)
4351 return ret;
4352
d1ccc66d
IM
4353 /* Bail out on silly large: */
4354 if (size > PAGE_SIZE)
d50dde5a
DF
4355 goto err_size;
4356
d1ccc66d
IM
4357 /* ABI compatibility quirk: */
4358 if (!size)
d50dde5a
DF
4359 size = SCHED_ATTR_SIZE_VER0;
4360
4361 if (size < SCHED_ATTR_SIZE_VER0)
4362 goto err_size;
4363
4364 /*
4365 * If we're handed a bigger struct than we know of,
4366 * ensure all the unknown bits are 0 - i.e. new
4367 * user-space does not rely on any kernel feature
4368 * extensions we dont know about yet.
4369 */
4370 if (size > sizeof(*attr)) {
4371 unsigned char __user *addr;
4372 unsigned char __user *end;
4373 unsigned char val;
4374
4375 addr = (void __user *)uattr + sizeof(*attr);
4376 end = (void __user *)uattr + size;
4377
4378 for (; addr < end; addr++) {
4379 ret = get_user(val, addr);
4380 if (ret)
4381 return ret;
4382 if (val)
4383 goto err_size;
4384 }
4385 size = sizeof(*attr);
4386 }
4387
4388 ret = copy_from_user(attr, uattr, size);
4389 if (ret)
4390 return -EFAULT;
4391
4392 /*
d1ccc66d 4393 * XXX: Do we want to be lenient like existing syscalls; or do we want
d50dde5a
DF
4394 * to be strict and return an error on out-of-bounds values?
4395 */
75e45d51 4396 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
d50dde5a 4397
e78c7bca 4398 return 0;
d50dde5a
DF
4399
4400err_size:
4401 put_user(sizeof(*attr), &uattr->size);
e78c7bca 4402 return -E2BIG;
d50dde5a
DF
4403}
4404
1da177e4
LT
4405/**
4406 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4407 * @pid: the pid in question.
4408 * @policy: new policy.
4409 * @param: structure containing the new RT priority.
e69f6186
YB
4410 *
4411 * Return: 0 on success. An error code otherwise.
1da177e4 4412 */
d1ccc66d 4413SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
1da177e4 4414{
c21761f1
JB
4415 if (policy < 0)
4416 return -EINVAL;
4417
1da177e4
LT
4418 return do_sched_setscheduler(pid, policy, param);
4419}
4420
4421/**
4422 * sys_sched_setparam - set/change the RT priority of a thread
4423 * @pid: the pid in question.
4424 * @param: structure containing the new RT priority.
e69f6186
YB
4425 *
4426 * Return: 0 on success. An error code otherwise.
1da177e4 4427 */
5add95d4 4428SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 4429{
c13db6b1 4430 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
1da177e4
LT
4431}
4432
d50dde5a
DF
4433/**
4434 * sys_sched_setattr - same as above, but with extended sched_attr
4435 * @pid: the pid in question.
5778fccf 4436 * @uattr: structure containing the extended parameters.
db66d756 4437 * @flags: for future extension.
d50dde5a 4438 */
6d35ab48
PZ
4439SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4440 unsigned int, flags)
d50dde5a
DF
4441{
4442 struct sched_attr attr;
4443 struct task_struct *p;
4444 int retval;
4445
6d35ab48 4446 if (!uattr || pid < 0 || flags)
d50dde5a
DF
4447 return -EINVAL;
4448
143cf23d
MK
4449 retval = sched_copy_attr(uattr, &attr);
4450 if (retval)
4451 return retval;
d50dde5a 4452
b14ed2c2 4453 if ((int)attr.sched_policy < 0)
dbdb2275 4454 return -EINVAL;
d50dde5a
DF
4455
4456 rcu_read_lock();
4457 retval = -ESRCH;
4458 p = find_process_by_pid(pid);
4459 if (p != NULL)
4460 retval = sched_setattr(p, &attr);
4461 rcu_read_unlock();
4462
4463 return retval;
4464}
4465
1da177e4
LT
4466/**
4467 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4468 * @pid: the pid in question.
e69f6186
YB
4469 *
4470 * Return: On success, the policy of the thread. Otherwise, a negative error
4471 * code.
1da177e4 4472 */
5add95d4 4473SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
1da177e4 4474{
36c8b586 4475 struct task_struct *p;
3a5c359a 4476 int retval;
1da177e4
LT
4477
4478 if (pid < 0)
3a5c359a 4479 return -EINVAL;
1da177e4
LT
4480
4481 retval = -ESRCH;
5fe85be0 4482 rcu_read_lock();
1da177e4
LT
4483 p = find_process_by_pid(pid);
4484 if (p) {
4485 retval = security_task_getscheduler(p);
4486 if (!retval)
ca94c442
LP
4487 retval = p->policy
4488 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
1da177e4 4489 }
5fe85be0 4490 rcu_read_unlock();
1da177e4
LT
4491 return retval;
4492}
4493
4494/**
ca94c442 4495 * sys_sched_getparam - get the RT priority of a thread
1da177e4
LT
4496 * @pid: the pid in question.
4497 * @param: structure containing the RT priority.
e69f6186
YB
4498 *
4499 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4500 * code.
1da177e4 4501 */
5add95d4 4502SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
1da177e4 4503{
ce5f7f82 4504 struct sched_param lp = { .sched_priority = 0 };
36c8b586 4505 struct task_struct *p;
3a5c359a 4506 int retval;
1da177e4
LT
4507
4508 if (!param || pid < 0)
3a5c359a 4509 return -EINVAL;
1da177e4 4510
5fe85be0 4511 rcu_read_lock();
1da177e4
LT
4512 p = find_process_by_pid(pid);
4513 retval = -ESRCH;
4514 if (!p)
4515 goto out_unlock;
4516
4517 retval = security_task_getscheduler(p);
4518 if (retval)
4519 goto out_unlock;
4520
ce5f7f82
PZ
4521 if (task_has_rt_policy(p))
4522 lp.sched_priority = p->rt_priority;
5fe85be0 4523 rcu_read_unlock();
1da177e4
LT
4524
4525 /*
4526 * This one might sleep, we cannot do it with a spinlock held ...
4527 */
4528 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4529
1da177e4
LT
4530 return retval;
4531
4532out_unlock:
5fe85be0 4533 rcu_read_unlock();
1da177e4
LT
4534 return retval;
4535}
4536
d50dde5a
DF
4537static int sched_read_attr(struct sched_attr __user *uattr,
4538 struct sched_attr *attr,
4539 unsigned int usize)
4540{
4541 int ret;
4542
4543 if (!access_ok(VERIFY_WRITE, uattr, usize))
4544 return -EFAULT;
4545
4546 /*
4547 * If we're handed a smaller struct than we know of,
4548 * ensure all the unknown bits are 0 - i.e. old
4549 * user-space does not get uncomplete information.
4550 */
4551 if (usize < sizeof(*attr)) {
4552 unsigned char *addr;
4553 unsigned char *end;
4554
4555 addr = (void *)attr + usize;
4556 end = (void *)attr + sizeof(*attr);
4557
4558 for (; addr < end; addr++) {
4559 if (*addr)
22400674 4560 return -EFBIG;
d50dde5a
DF
4561 }
4562
4563 attr->size = usize;
4564 }
4565
4efbc454 4566 ret = copy_to_user(uattr, attr, attr->size);
d50dde5a
DF
4567 if (ret)
4568 return -EFAULT;
4569
22400674 4570 return 0;
d50dde5a
DF
4571}
4572
4573/**
aab03e05 4574 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
d50dde5a 4575 * @pid: the pid in question.
5778fccf 4576 * @uattr: structure containing the extended parameters.
d50dde5a 4577 * @size: sizeof(attr) for fwd/bwd comp.
db66d756 4578 * @flags: for future extension.
d50dde5a 4579 */
6d35ab48
PZ
4580SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4581 unsigned int, size, unsigned int, flags)
d50dde5a
DF
4582{
4583 struct sched_attr attr = {
4584 .size = sizeof(struct sched_attr),
4585 };
4586 struct task_struct *p;
4587 int retval;
4588
4589 if (!uattr || pid < 0 || size > PAGE_SIZE ||
6d35ab48 4590 size < SCHED_ATTR_SIZE_VER0 || flags)
d50dde5a
DF
4591 return -EINVAL;
4592
4593 rcu_read_lock();
4594 p = find_process_by_pid(pid);
4595 retval = -ESRCH;
4596 if (!p)
4597 goto out_unlock;
4598
4599 retval = security_task_getscheduler(p);
4600 if (retval)
4601 goto out_unlock;
4602
4603 attr.sched_policy = p->policy;
7479f3c9
PZ
4604 if (p->sched_reset_on_fork)
4605 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
aab03e05
DF
4606 if (task_has_dl_policy(p))
4607 __getparam_dl(p, &attr);
4608 else if (task_has_rt_policy(p))
d50dde5a
DF
4609 attr.sched_priority = p->rt_priority;
4610 else
d0ea0268 4611 attr.sched_nice = task_nice(p);
d50dde5a
DF
4612
4613 rcu_read_unlock();
4614
4615 retval = sched_read_attr(uattr, &attr, size);
4616 return retval;
4617
4618out_unlock:
4619 rcu_read_unlock();
4620 return retval;
4621}
4622
96f874e2 4623long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
1da177e4 4624{
5a16f3d3 4625 cpumask_var_t cpus_allowed, new_mask;
36c8b586
IM
4626 struct task_struct *p;
4627 int retval;
1da177e4 4628
23f5d142 4629 rcu_read_lock();
1da177e4
LT
4630
4631 p = find_process_by_pid(pid);
4632 if (!p) {
23f5d142 4633 rcu_read_unlock();
1da177e4
LT
4634 return -ESRCH;
4635 }
4636
23f5d142 4637 /* Prevent p going away */
1da177e4 4638 get_task_struct(p);
23f5d142 4639 rcu_read_unlock();
1da177e4 4640
14a40ffc
TH
4641 if (p->flags & PF_NO_SETAFFINITY) {
4642 retval = -EINVAL;
4643 goto out_put_task;
4644 }
5a16f3d3
RR
4645 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4646 retval = -ENOMEM;
4647 goto out_put_task;
4648 }
4649 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4650 retval = -ENOMEM;
4651 goto out_free_cpus_allowed;
4652 }
1da177e4 4653 retval = -EPERM;
4c44aaaf
EB
4654 if (!check_same_owner(p)) {
4655 rcu_read_lock();
4656 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4657 rcu_read_unlock();
16303ab2 4658 goto out_free_new_mask;
4c44aaaf
EB
4659 }
4660 rcu_read_unlock();
4661 }
1da177e4 4662
b0ae1981 4663 retval = security_task_setscheduler(p);
e7834f8f 4664 if (retval)
16303ab2 4665 goto out_free_new_mask;
e7834f8f 4666
e4099a5e
PZ
4667
4668 cpuset_cpus_allowed(p, cpus_allowed);
4669 cpumask_and(new_mask, in_mask, cpus_allowed);
4670
332ac17e
DF
4671 /*
4672 * Since bandwidth control happens on root_domain basis,
4673 * if admission test is enabled, we only admit -deadline
4674 * tasks allowed to run on all the CPUs in the task's
4675 * root_domain.
4676 */
4677#ifdef CONFIG_SMP
f1e3a093
KT
4678 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4679 rcu_read_lock();
4680 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
332ac17e 4681 retval = -EBUSY;
f1e3a093 4682 rcu_read_unlock();
16303ab2 4683 goto out_free_new_mask;
332ac17e 4684 }
f1e3a093 4685 rcu_read_unlock();
332ac17e
DF
4686 }
4687#endif
49246274 4688again:
25834c73 4689 retval = __set_cpus_allowed_ptr(p, new_mask, true);
1da177e4 4690
8707d8b8 4691 if (!retval) {
5a16f3d3
RR
4692 cpuset_cpus_allowed(p, cpus_allowed);
4693 if (!cpumask_subset(new_mask, cpus_allowed)) {
8707d8b8
PM
4694 /*
4695 * We must have raced with a concurrent cpuset
4696 * update. Just reset the cpus_allowed to the
4697 * cpuset's cpus_allowed
4698 */
5a16f3d3 4699 cpumask_copy(new_mask, cpus_allowed);
8707d8b8
PM
4700 goto again;
4701 }
4702 }
16303ab2 4703out_free_new_mask:
5a16f3d3
RR
4704 free_cpumask_var(new_mask);
4705out_free_cpus_allowed:
4706 free_cpumask_var(cpus_allowed);
4707out_put_task:
1da177e4 4708 put_task_struct(p);
1da177e4
LT
4709 return retval;
4710}
4711
4712static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
96f874e2 4713 struct cpumask *new_mask)
1da177e4 4714{
96f874e2
RR
4715 if (len < cpumask_size())
4716 cpumask_clear(new_mask);
4717 else if (len > cpumask_size())
4718 len = cpumask_size();
4719
1da177e4
LT
4720 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4721}
4722
4723/**
d1ccc66d 4724 * sys_sched_setaffinity - set the CPU affinity of a process
1da177e4
LT
4725 * @pid: pid of the process
4726 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 4727 * @user_mask_ptr: user-space pointer to the new CPU mask
e69f6186
YB
4728 *
4729 * Return: 0 on success. An error code otherwise.
1da177e4 4730 */
5add95d4
HC
4731SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4732 unsigned long __user *, user_mask_ptr)
1da177e4 4733{
5a16f3d3 4734 cpumask_var_t new_mask;
1da177e4
LT
4735 int retval;
4736
5a16f3d3
RR
4737 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4738 return -ENOMEM;
1da177e4 4739
5a16f3d3
RR
4740 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4741 if (retval == 0)
4742 retval = sched_setaffinity(pid, new_mask);
4743 free_cpumask_var(new_mask);
4744 return retval;
1da177e4
LT
4745}
4746
96f874e2 4747long sched_getaffinity(pid_t pid, struct cpumask *mask)
1da177e4 4748{
36c8b586 4749 struct task_struct *p;
31605683 4750 unsigned long flags;
1da177e4 4751 int retval;
1da177e4 4752
23f5d142 4753 rcu_read_lock();
1da177e4
LT
4754
4755 retval = -ESRCH;
4756 p = find_process_by_pid(pid);
4757 if (!p)
4758 goto out_unlock;
4759
e7834f8f
DQ
4760 retval = security_task_getscheduler(p);
4761 if (retval)
4762 goto out_unlock;
4763
013fdb80 4764 raw_spin_lock_irqsave(&p->pi_lock, flags);
6acce3ef 4765 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
013fdb80 4766 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
4767
4768out_unlock:
23f5d142 4769 rcu_read_unlock();
1da177e4 4770
9531b62f 4771 return retval;
1da177e4
LT
4772}
4773
4774/**
d1ccc66d 4775 * sys_sched_getaffinity - get the CPU affinity of a process
1da177e4
LT
4776 * @pid: pid of the process
4777 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
d1ccc66d 4778 * @user_mask_ptr: user-space pointer to hold the current CPU mask
e69f6186 4779 *
599b4840
ZW
4780 * Return: size of CPU mask copied to user_mask_ptr on success. An
4781 * error code otherwise.
1da177e4 4782 */
5add95d4
HC
4783SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4784 unsigned long __user *, user_mask_ptr)
1da177e4
LT
4785{
4786 int ret;
f17c8607 4787 cpumask_var_t mask;
1da177e4 4788
84fba5ec 4789 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
cd3d8031
KM
4790 return -EINVAL;
4791 if (len & (sizeof(unsigned long)-1))
1da177e4
LT
4792 return -EINVAL;
4793
f17c8607
RR
4794 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4795 return -ENOMEM;
1da177e4 4796
f17c8607
RR
4797 ret = sched_getaffinity(pid, mask);
4798 if (ret == 0) {
8bc037fb 4799 size_t retlen = min_t(size_t, len, cpumask_size());
cd3d8031
KM
4800
4801 if (copy_to_user(user_mask_ptr, mask, retlen))
f17c8607
RR
4802 ret = -EFAULT;
4803 else
cd3d8031 4804 ret = retlen;
f17c8607
RR
4805 }
4806 free_cpumask_var(mask);
1da177e4 4807
f17c8607 4808 return ret;
1da177e4
LT
4809}
4810
4811/**
4812 * sys_sched_yield - yield the current processor to other threads.
4813 *
dd41f596
IM
4814 * This function yields the current CPU to other tasks. If there are no
4815 * other threads running on this CPU then this function will return.
e69f6186
YB
4816 *
4817 * Return: 0.
1da177e4 4818 */
5add95d4 4819SYSCALL_DEFINE0(sched_yield)
1da177e4 4820{
8a8c69c3
PZ
4821 struct rq_flags rf;
4822 struct rq *rq;
4823
4824 local_irq_disable();
4825 rq = this_rq();
4826 rq_lock(rq, &rf);
1da177e4 4827
ae92882e 4828 schedstat_inc(rq->yld_count);
4530d7ab 4829 current->sched_class->yield_task(rq);
1da177e4
LT
4830
4831 /*
4832 * Since we are going to call schedule() anyway, there's
4833 * no need to preempt or enable interrupts:
4834 */
8a8c69c3
PZ
4835 preempt_disable();
4836 rq_unlock(rq, &rf);
ba74c144 4837 sched_preempt_enable_no_resched();
1da177e4
LT
4838
4839 schedule();
4840
4841 return 0;
4842}
4843
35a773a0 4844#ifndef CONFIG_PREEMPT
02b67cc3 4845int __sched _cond_resched(void)
1da177e4 4846{
fe32d3cd 4847 if (should_resched(0)) {
a18b5d01 4848 preempt_schedule_common();
1da177e4
LT
4849 return 1;
4850 }
f79c3ad6 4851 rcu_all_qs();
1da177e4
LT
4852 return 0;
4853}
02b67cc3 4854EXPORT_SYMBOL(_cond_resched);
35a773a0 4855#endif
1da177e4
LT
4856
4857/*
613afbf8 4858 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
1da177e4
LT
4859 * call schedule, and on return reacquire the lock.
4860 *
41a2d6cf 4861 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
1da177e4
LT
4862 * operations here to prevent schedule() from being called twice (once via
4863 * spin_unlock(), once by hand).
4864 */
613afbf8 4865int __cond_resched_lock(spinlock_t *lock)
1da177e4 4866{
fe32d3cd 4867 int resched = should_resched(PREEMPT_LOCK_OFFSET);
6df3cecb
JK
4868 int ret = 0;
4869
f607c668
PZ
4870 lockdep_assert_held(lock);
4871
4a81e832 4872 if (spin_needbreak(lock) || resched) {
1da177e4 4873 spin_unlock(lock);
d86ee480 4874 if (resched)
a18b5d01 4875 preempt_schedule_common();
95c354fe
NP
4876 else
4877 cpu_relax();
6df3cecb 4878 ret = 1;
1da177e4 4879 spin_lock(lock);
1da177e4 4880 }
6df3cecb 4881 return ret;
1da177e4 4882}
613afbf8 4883EXPORT_SYMBOL(__cond_resched_lock);
1da177e4 4884
613afbf8 4885int __sched __cond_resched_softirq(void)
1da177e4
LT
4886{
4887 BUG_ON(!in_softirq());
4888
fe32d3cd 4889 if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
98d82567 4890 local_bh_enable();
a18b5d01 4891 preempt_schedule_common();
1da177e4
LT
4892 local_bh_disable();
4893 return 1;
4894 }
4895 return 0;
4896}
613afbf8 4897EXPORT_SYMBOL(__cond_resched_softirq);
1da177e4 4898
1da177e4
LT
4899/**
4900 * yield - yield the current processor to other threads.
4901 *
8e3fabfd
PZ
4902 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4903 *
4904 * The scheduler is at all times free to pick the calling task as the most
4905 * eligible task to run, if removing the yield() call from your code breaks
4906 * it, its already broken.
4907 *
4908 * Typical broken usage is:
4909 *
4910 * while (!event)
d1ccc66d 4911 * yield();
8e3fabfd
PZ
4912 *
4913 * where one assumes that yield() will let 'the other' process run that will
4914 * make event true. If the current task is a SCHED_FIFO task that will never
4915 * happen. Never use yield() as a progress guarantee!!
4916 *
4917 * If you want to use yield() to wait for something, use wait_event().
4918 * If you want to use yield() to be 'nice' for others, use cond_resched().
4919 * If you still want to use yield(), do not!
1da177e4
LT
4920 */
4921void __sched yield(void)
4922{
4923 set_current_state(TASK_RUNNING);
4924 sys_sched_yield();
4925}
1da177e4
LT
4926EXPORT_SYMBOL(yield);
4927
d95f4122
MG
4928/**
4929 * yield_to - yield the current processor to another thread in
4930 * your thread group, or accelerate that thread toward the
4931 * processor it's on.
16addf95
RD
4932 * @p: target task
4933 * @preempt: whether task preemption is allowed or not
d95f4122
MG
4934 *
4935 * It's the caller's job to ensure that the target task struct
4936 * can't go away on us before we can do any checks.
4937 *
e69f6186 4938 * Return:
7b270f60
PZ
4939 * true (>0) if we indeed boosted the target task.
4940 * false (0) if we failed to boost the target.
4941 * -ESRCH if there's no task to yield to.
d95f4122 4942 */
fa93384f 4943int __sched yield_to(struct task_struct *p, bool preempt)
d95f4122
MG
4944{
4945 struct task_struct *curr = current;
4946 struct rq *rq, *p_rq;
4947 unsigned long flags;
c3c18640 4948 int yielded = 0;
d95f4122
MG
4949
4950 local_irq_save(flags);
4951 rq = this_rq();
4952
4953again:
4954 p_rq = task_rq(p);
7b270f60
PZ
4955 /*
4956 * If we're the only runnable task on the rq and target rq also
4957 * has only one task, there's absolutely no point in yielding.
4958 */
4959 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4960 yielded = -ESRCH;
4961 goto out_irq;
4962 }
4963
d95f4122 4964 double_rq_lock(rq, p_rq);
39e24d8f 4965 if (task_rq(p) != p_rq) {
d95f4122
MG
4966 double_rq_unlock(rq, p_rq);
4967 goto again;
4968 }
4969
4970 if (!curr->sched_class->yield_to_task)
7b270f60 4971 goto out_unlock;
d95f4122
MG
4972
4973 if (curr->sched_class != p->sched_class)
7b270f60 4974 goto out_unlock;
d95f4122
MG
4975
4976 if (task_running(p_rq, p) || p->state)
7b270f60 4977 goto out_unlock;
d95f4122
MG
4978
4979 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
6d1cafd8 4980 if (yielded) {
ae92882e 4981 schedstat_inc(rq->yld_count);
6d1cafd8
VP
4982 /*
4983 * Make p's CPU reschedule; pick_next_entity takes care of
4984 * fairness.
4985 */
4986 if (preempt && rq != p_rq)
8875125e 4987 resched_curr(p_rq);
6d1cafd8 4988 }
d95f4122 4989
7b270f60 4990out_unlock:
d95f4122 4991 double_rq_unlock(rq, p_rq);
7b270f60 4992out_irq:
d95f4122
MG
4993 local_irq_restore(flags);
4994
7b270f60 4995 if (yielded > 0)
d95f4122
MG
4996 schedule();
4997
4998 return yielded;
4999}
5000EXPORT_SYMBOL_GPL(yield_to);
5001
10ab5643
TH
5002int io_schedule_prepare(void)
5003{
5004 int old_iowait = current->in_iowait;
5005
5006 current->in_iowait = 1;
5007 blk_schedule_flush_plug(current);
5008
5009 return old_iowait;
5010}
5011
5012void io_schedule_finish(int token)
5013{
5014 current->in_iowait = token;
5015}
5016
1da177e4 5017/*
41a2d6cf 5018 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
1da177e4 5019 * that process accounting knows that this is a task in IO wait state.
1da177e4 5020 */
1da177e4
LT
5021long __sched io_schedule_timeout(long timeout)
5022{
10ab5643 5023 int token;
1da177e4
LT
5024 long ret;
5025
10ab5643 5026 token = io_schedule_prepare();
1da177e4 5027 ret = schedule_timeout(timeout);
10ab5643 5028 io_schedule_finish(token);
9cff8ade 5029
1da177e4
LT
5030 return ret;
5031}
9cff8ade 5032EXPORT_SYMBOL(io_schedule_timeout);
1da177e4 5033
10ab5643
TH
5034void io_schedule(void)
5035{
5036 int token;
5037
5038 token = io_schedule_prepare();
5039 schedule();
5040 io_schedule_finish(token);
5041}
5042EXPORT_SYMBOL(io_schedule);
5043
1da177e4
LT
5044/**
5045 * sys_sched_get_priority_max - return maximum RT priority.
5046 * @policy: scheduling class.
5047 *
e69f6186
YB
5048 * Return: On success, this syscall returns the maximum
5049 * rt_priority that can be used by a given scheduling class.
5050 * On failure, a negative error code is returned.
1da177e4 5051 */
5add95d4 5052SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
1da177e4
LT
5053{
5054 int ret = -EINVAL;
5055
5056 switch (policy) {
5057 case SCHED_FIFO:
5058 case SCHED_RR:
5059 ret = MAX_USER_RT_PRIO-1;
5060 break;
aab03e05 5061 case SCHED_DEADLINE:
1da177e4 5062 case SCHED_NORMAL:
b0a9499c 5063 case SCHED_BATCH:
dd41f596 5064 case SCHED_IDLE:
1da177e4
LT
5065 ret = 0;
5066 break;
5067 }
5068 return ret;
5069}
5070
5071/**
5072 * sys_sched_get_priority_min - return minimum RT priority.
5073 * @policy: scheduling class.
5074 *
e69f6186
YB
5075 * Return: On success, this syscall returns the minimum
5076 * rt_priority that can be used by a given scheduling class.
5077 * On failure, a negative error code is returned.
1da177e4 5078 */
5add95d4 5079SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
1da177e4
LT
5080{
5081 int ret = -EINVAL;
5082
5083 switch (policy) {
5084 case SCHED_FIFO:
5085 case SCHED_RR:
5086 ret = 1;
5087 break;
aab03e05 5088 case SCHED_DEADLINE:
1da177e4 5089 case SCHED_NORMAL:
b0a9499c 5090 case SCHED_BATCH:
dd41f596 5091 case SCHED_IDLE:
1da177e4
LT
5092 ret = 0;
5093 }
5094 return ret;
5095}
5096
abca5fc5 5097static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
1da177e4 5098{
36c8b586 5099 struct task_struct *p;
a4ec24b4 5100 unsigned int time_slice;
eb580751 5101 struct rq_flags rf;
dba091b9 5102 struct rq *rq;
3a5c359a 5103 int retval;
1da177e4
LT
5104
5105 if (pid < 0)
3a5c359a 5106 return -EINVAL;
1da177e4
LT
5107
5108 retval = -ESRCH;
1a551ae7 5109 rcu_read_lock();
1da177e4
LT
5110 p = find_process_by_pid(pid);
5111 if (!p)
5112 goto out_unlock;
5113
5114 retval = security_task_getscheduler(p);
5115 if (retval)
5116 goto out_unlock;
5117
eb580751 5118 rq = task_rq_lock(p, &rf);
a57beec5
PZ
5119 time_slice = 0;
5120 if (p->sched_class->get_rr_interval)
5121 time_slice = p->sched_class->get_rr_interval(rq, p);
eb580751 5122 task_rq_unlock(rq, p, &rf);
a4ec24b4 5123
1a551ae7 5124 rcu_read_unlock();
abca5fc5
AV
5125 jiffies_to_timespec64(time_slice, t);
5126 return 0;
3a5c359a 5127
1da177e4 5128out_unlock:
1a551ae7 5129 rcu_read_unlock();
1da177e4
LT
5130 return retval;
5131}
5132
2064a5ab
RD
5133/**
5134 * sys_sched_rr_get_interval - return the default timeslice of a process.
5135 * @pid: pid of the process.
5136 * @interval: userspace pointer to the timeslice value.
5137 *
5138 * this syscall writes the default timeslice value of a given process
5139 * into the user-space timespec buffer. A value of '0' means infinity.
5140 *
5141 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5142 * an error code.
5143 */
abca5fc5
AV
5144SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5145 struct timespec __user *, interval)
5146{
5147 struct timespec64 t;
5148 int retval = sched_rr_get_interval(pid, &t);
5149
5150 if (retval == 0)
5151 retval = put_timespec64(&t, interval);
5152
5153 return retval;
5154}
5155
5156#ifdef CONFIG_COMPAT
5157COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
5158 compat_pid_t, pid,
5159 struct compat_timespec __user *, interval)
5160{
5161 struct timespec64 t;
5162 int retval = sched_rr_get_interval(pid, &t);
5163
5164 if (retval == 0)
5165 retval = compat_put_timespec64(&t, interval);
5166 return retval;
5167}
5168#endif
5169
82a1fcb9 5170void sched_show_task(struct task_struct *p)
1da177e4 5171{
1da177e4 5172 unsigned long free = 0;
4e79752c 5173 int ppid;
c930b2c0 5174
38200502
TH
5175 if (!try_get_task_stack(p))
5176 return;
20435d84
XX
5177
5178 printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
5179
5180 if (p->state == TASK_RUNNING)
3df0fc5b 5181 printk(KERN_CONT " running task ");
1da177e4 5182#ifdef CONFIG_DEBUG_STACK_USAGE
7c9f8861 5183 free = stack_not_used(p);
1da177e4 5184#endif
a90e984c 5185 ppid = 0;
4e79752c 5186 rcu_read_lock();
a90e984c
ON
5187 if (pid_alive(p))
5188 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4e79752c 5189 rcu_read_unlock();
3df0fc5b 5190 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4e79752c 5191 task_pid_nr(p), ppid,
aa47b7e0 5192 (unsigned long)task_thread_info(p)->flags);
1da177e4 5193
3d1cb205 5194 print_worker_info(KERN_INFO, p);
5fb5e6de 5195 show_stack(p, NULL);
38200502 5196 put_task_stack(p);
1da177e4 5197}
0032f4e8 5198EXPORT_SYMBOL_GPL(sched_show_task);
1da177e4 5199
5d68cc95
PZ
5200static inline bool
5201state_filter_match(unsigned long state_filter, struct task_struct *p)
5202{
5203 /* no filter, everything matches */
5204 if (!state_filter)
5205 return true;
5206
5207 /* filter, but doesn't match */
5208 if (!(p->state & state_filter))
5209 return false;
5210
5211 /*
5212 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5213 * TASK_KILLABLE).
5214 */
5215 if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
5216 return false;
5217
5218 return true;
5219}
5220
5221
e59e2ae2 5222void show_state_filter(unsigned long state_filter)
1da177e4 5223{
36c8b586 5224 struct task_struct *g, *p;
1da177e4 5225
4bd77321 5226#if BITS_PER_LONG == 32
3df0fc5b
PZ
5227 printk(KERN_INFO
5228 " task PC stack pid father\n");
1da177e4 5229#else
3df0fc5b
PZ
5230 printk(KERN_INFO
5231 " task PC stack pid father\n");
1da177e4 5232#endif
510f5acc 5233 rcu_read_lock();
5d07f420 5234 for_each_process_thread(g, p) {
1da177e4
LT
5235 /*
5236 * reset the NMI-timeout, listing all files on a slow
25985edc 5237 * console might take a lot of time:
57675cb9
AR
5238 * Also, reset softlockup watchdogs on all CPUs, because
5239 * another CPU might be blocked waiting for us to process
5240 * an IPI.
1da177e4
LT
5241 */
5242 touch_nmi_watchdog();
57675cb9 5243 touch_all_softlockup_watchdogs();
5d68cc95 5244 if (state_filter_match(state_filter, p))
82a1fcb9 5245 sched_show_task(p);
5d07f420 5246 }
1da177e4 5247
dd41f596 5248#ifdef CONFIG_SCHED_DEBUG
fb90a6e9
RV
5249 if (!state_filter)
5250 sysrq_sched_debug_show();
dd41f596 5251#endif
510f5acc 5252 rcu_read_unlock();
e59e2ae2
IM
5253 /*
5254 * Only show locks if all tasks are dumped:
5255 */
93335a21 5256 if (!state_filter)
e59e2ae2 5257 debug_show_all_locks();
1da177e4
LT
5258}
5259
f340c0d1
IM
5260/**
5261 * init_idle - set up an idle thread for a given CPU
5262 * @idle: task in question
d1ccc66d 5263 * @cpu: CPU the idle task belongs to
f340c0d1
IM
5264 *
5265 * NOTE: this function does not set the idle thread's NEED_RESCHED
5266 * flag, to make booting more robust.
5267 */
0db0628d 5268void init_idle(struct task_struct *idle, int cpu)
1da177e4 5269{
70b97a7f 5270 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
5271 unsigned long flags;
5272
25834c73
PZ
5273 raw_spin_lock_irqsave(&idle->pi_lock, flags);
5274 raw_spin_lock(&rq->lock);
5cbd54ef 5275
5e1576ed 5276 __sched_fork(0, idle);
06b83b5f 5277 idle->state = TASK_RUNNING;
dd41f596 5278 idle->se.exec_start = sched_clock();
c1de45ca 5279 idle->flags |= PF_IDLE;
dd41f596 5280
e1b77c92
MR
5281 kasan_unpoison_task_stack(idle);
5282
de9b8f5d
PZ
5283#ifdef CONFIG_SMP
5284 /*
5285 * Its possible that init_idle() gets called multiple times on a task,
5286 * in that case do_set_cpus_allowed() will not do the right thing.
5287 *
5288 * And since this is boot we can forgo the serialization.
5289 */
5290 set_cpus_allowed_common(idle, cpumask_of(cpu));
5291#endif
6506cf6c
PZ
5292 /*
5293 * We're having a chicken and egg problem, even though we are
d1ccc66d 5294 * holding rq->lock, the CPU isn't yet set to this CPU so the
6506cf6c
PZ
5295 * lockdep check in task_group() will fail.
5296 *
5297 * Similar case to sched_fork(). / Alternatively we could
5298 * use task_rq_lock() here and obtain the other rq->lock.
5299 *
5300 * Silence PROVE_RCU
5301 */
5302 rcu_read_lock();
dd41f596 5303 __set_task_cpu(idle, cpu);
6506cf6c 5304 rcu_read_unlock();
1da177e4 5305
1da177e4 5306 rq->curr = rq->idle = idle;
da0c1e65 5307 idle->on_rq = TASK_ON_RQ_QUEUED;
de9b8f5d 5308#ifdef CONFIG_SMP
3ca7a440 5309 idle->on_cpu = 1;
4866cde0 5310#endif
25834c73
PZ
5311 raw_spin_unlock(&rq->lock);
5312 raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
1da177e4
LT
5313
5314 /* Set the preempt count _outside_ the spinlocks! */
01028747 5315 init_idle_preempt_count(idle, cpu);
55cd5340 5316
dd41f596
IM
5317 /*
5318 * The idle tasks have their own, simple scheduling class:
5319 */
5320 idle->sched_class = &idle_sched_class;
868baf07 5321 ftrace_graph_init_idle_task(idle, cpu);
45eacc69 5322 vtime_init_idle(idle, cpu);
de9b8f5d 5323#ifdef CONFIG_SMP
f1c6f1a7
CE
5324 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5325#endif
19978ca6
IM
5326}
5327
e1d4eeec
NP
5328#ifdef CONFIG_SMP
5329
f82f8042
JL
5330int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5331 const struct cpumask *trial)
5332{
06a76fe0 5333 int ret = 1;
f82f8042 5334
bb2bc55a
MG
5335 if (!cpumask_weight(cur))
5336 return ret;
5337
06a76fe0 5338 ret = dl_cpuset_cpumask_can_shrink(cur, trial);
f82f8042
JL
5339
5340 return ret;
5341}
5342
7f51412a
JL
5343int task_can_attach(struct task_struct *p,
5344 const struct cpumask *cs_cpus_allowed)
5345{
5346 int ret = 0;
5347
5348 /*
5349 * Kthreads which disallow setaffinity shouldn't be moved
d1ccc66d 5350 * to a new cpuset; we don't want to change their CPU
7f51412a
JL
5351 * affinity and isolating such threads by their set of
5352 * allowed nodes is unnecessary. Thus, cpusets are not
5353 * applicable for such threads. This prevents checking for
5354 * success of set_cpus_allowed_ptr() on all attached tasks
5355 * before cpus_allowed may be changed.
5356 */
5357 if (p->flags & PF_NO_SETAFFINITY) {
5358 ret = -EINVAL;
5359 goto out;
5360 }
5361
7f51412a 5362 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
06a76fe0
NP
5363 cs_cpus_allowed))
5364 ret = dl_task_can_attach(p, cs_cpus_allowed);
7f51412a 5365
7f51412a
JL
5366out:
5367 return ret;
5368}
5369
f2cb1360 5370bool sched_smp_initialized __read_mostly;
e26fbffd 5371
e6628d5b
MG
5372#ifdef CONFIG_NUMA_BALANCING
5373/* Migrate current task p to target_cpu */
5374int migrate_task_to(struct task_struct *p, int target_cpu)
5375{
5376 struct migration_arg arg = { p, target_cpu };
5377 int curr_cpu = task_cpu(p);
5378
5379 if (curr_cpu == target_cpu)
5380 return 0;
5381
0c98d344 5382 if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
e6628d5b
MG
5383 return -EINVAL;
5384
5385 /* TODO: This is not properly updating schedstats */
5386
286549dc 5387 trace_sched_move_numa(p, curr_cpu, target_cpu);
e6628d5b
MG
5388 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5389}
0ec8aa00
PZ
5390
5391/*
5392 * Requeue a task on a given node and accurately track the number of NUMA
5393 * tasks on the runqueues
5394 */
5395void sched_setnuma(struct task_struct *p, int nid)
5396{
da0c1e65 5397 bool queued, running;
eb580751
PZ
5398 struct rq_flags rf;
5399 struct rq *rq;
0ec8aa00 5400
eb580751 5401 rq = task_rq_lock(p, &rf);
da0c1e65 5402 queued = task_on_rq_queued(p);
0ec8aa00
PZ
5403 running = task_current(rq, p);
5404
da0c1e65 5405 if (queued)
1de64443 5406 dequeue_task(rq, p, DEQUEUE_SAVE);
0ec8aa00 5407 if (running)
f3cd1c4e 5408 put_prev_task(rq, p);
0ec8aa00
PZ
5409
5410 p->numa_preferred_nid = nid;
0ec8aa00 5411
da0c1e65 5412 if (queued)
7134b3e9 5413 enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
a399d233 5414 if (running)
b2bf6c31 5415 set_curr_task(rq, p);
eb580751 5416 task_rq_unlock(rq, p, &rf);
0ec8aa00 5417}
5cc389bc 5418#endif /* CONFIG_NUMA_BALANCING */
f7b4cddc 5419
1da177e4 5420#ifdef CONFIG_HOTPLUG_CPU
054b9108 5421/*
d1ccc66d 5422 * Ensure that the idle task is using init_mm right before its CPU goes
48c5ccae 5423 * offline.
054b9108 5424 */
48c5ccae 5425void idle_task_exit(void)
1da177e4 5426{
48c5ccae 5427 struct mm_struct *mm = current->active_mm;
e76bd8d9 5428
48c5ccae 5429 BUG_ON(cpu_online(smp_processor_id()));
e76bd8d9 5430
a53efe5f 5431 if (mm != &init_mm) {
252d2a41 5432 switch_mm(mm, &init_mm, current);
a53efe5f
MS
5433 finish_arch_post_lock_switch();
5434 }
48c5ccae 5435 mmdrop(mm);
1da177e4
LT
5436}
5437
5438/*
5d180232
PZ
5439 * Since this CPU is going 'away' for a while, fold any nr_active delta
5440 * we might have. Assumes we're called after migrate_tasks() so that the
d60585c5
TG
5441 * nr_active count is stable. We need to take the teardown thread which
5442 * is calling this into account, so we hand in adjust = 1 to the load
5443 * calculation.
5d180232
PZ
5444 *
5445 * Also see the comment "Global load-average calculations".
1da177e4 5446 */
5d180232 5447static void calc_load_migrate(struct rq *rq)
1da177e4 5448{
d60585c5 5449 long delta = calc_load_fold_active(rq, 1);
5d180232
PZ
5450 if (delta)
5451 atomic_long_add(delta, &calc_load_tasks);
1da177e4
LT
5452}
5453
3f1d2a31
PZ
5454static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5455{
5456}
5457
5458static const struct sched_class fake_sched_class = {
5459 .put_prev_task = put_prev_task_fake,
5460};
5461
5462static struct task_struct fake_task = {
5463 /*
5464 * Avoid pull_{rt,dl}_task()
5465 */
5466 .prio = MAX_PRIO + 1,
5467 .sched_class = &fake_sched_class,
5468};
5469
48f24c4d 5470/*
48c5ccae
PZ
5471 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5472 * try_to_wake_up()->select_task_rq().
5473 *
5474 * Called with rq->lock held even though we'er in stop_machine() and
5475 * there's no concurrency possible, we hold the required locks anyway
5476 * because of lock validation efforts.
1da177e4 5477 */
8a8c69c3 5478static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
1da177e4 5479{
5e16bbc2 5480 struct rq *rq = dead_rq;
48c5ccae 5481 struct task_struct *next, *stop = rq->stop;
8a8c69c3 5482 struct rq_flags orf = *rf;
48c5ccae 5483 int dest_cpu;
1da177e4
LT
5484
5485 /*
48c5ccae
PZ
5486 * Fudge the rq selection such that the below task selection loop
5487 * doesn't get stuck on the currently eligible stop task.
5488 *
5489 * We're currently inside stop_machine() and the rq is either stuck
5490 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5491 * either way we should never end up calling schedule() until we're
5492 * done here.
1da177e4 5493 */
48c5ccae 5494 rq->stop = NULL;
48f24c4d 5495
77bd3970
FW
5496 /*
5497 * put_prev_task() and pick_next_task() sched
5498 * class method both need to have an up-to-date
5499 * value of rq->clock[_task]
5500 */
5501 update_rq_clock(rq);
5502
5e16bbc2 5503 for (;;) {
48c5ccae
PZ
5504 /*
5505 * There's this thread running, bail when that's the only
d1ccc66d 5506 * remaining thread:
48c5ccae
PZ
5507 */
5508 if (rq->nr_running == 1)
dd41f596 5509 break;
48c5ccae 5510
cbce1a68 5511 /*
d1ccc66d 5512 * pick_next_task() assumes pinned rq->lock:
cbce1a68 5513 */
8a8c69c3 5514 next = pick_next_task(rq, &fake_task, rf);
48c5ccae 5515 BUG_ON(!next);
5b713a3d 5516 put_prev_task(rq, next);
e692ab53 5517
5473e0cc
WL
5518 /*
5519 * Rules for changing task_struct::cpus_allowed are holding
5520 * both pi_lock and rq->lock, such that holding either
5521 * stabilizes the mask.
5522 *
5523 * Drop rq->lock is not quite as disastrous as it usually is
5524 * because !cpu_active at this point, which means load-balance
5525 * will not interfere. Also, stop-machine.
5526 */
8a8c69c3 5527 rq_unlock(rq, rf);
5473e0cc 5528 raw_spin_lock(&next->pi_lock);
8a8c69c3 5529 rq_relock(rq, rf);
5473e0cc
WL
5530
5531 /*
5532 * Since we're inside stop-machine, _nothing_ should have
5533 * changed the task, WARN if weird stuff happened, because in
5534 * that case the above rq->lock drop is a fail too.
5535 */
5536 if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5537 raw_spin_unlock(&next->pi_lock);
5538 continue;
5539 }
5540
48c5ccae 5541 /* Find suitable destination for @next, with force if needed. */
5e16bbc2 5542 dest_cpu = select_fallback_rq(dead_rq->cpu, next);
8a8c69c3 5543 rq = __migrate_task(rq, rf, next, dest_cpu);
5e16bbc2 5544 if (rq != dead_rq) {
8a8c69c3 5545 rq_unlock(rq, rf);
5e16bbc2 5546 rq = dead_rq;
8a8c69c3
PZ
5547 *rf = orf;
5548 rq_relock(rq, rf);
5e16bbc2 5549 }
5473e0cc 5550 raw_spin_unlock(&next->pi_lock);
1da177e4 5551 }
dce48a84 5552
48c5ccae 5553 rq->stop = stop;
dce48a84 5554}
1da177e4
LT
5555#endif /* CONFIG_HOTPLUG_CPU */
5556
f2cb1360 5557void set_rq_online(struct rq *rq)
1f11eb6a
GH
5558{
5559 if (!rq->online) {
5560 const struct sched_class *class;
5561
c6c4927b 5562 cpumask_set_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5563 rq->online = 1;
5564
5565 for_each_class(class) {
5566 if (class->rq_online)
5567 class->rq_online(rq);
5568 }
5569 }
5570}
5571
f2cb1360 5572void set_rq_offline(struct rq *rq)
1f11eb6a
GH
5573{
5574 if (rq->online) {
5575 const struct sched_class *class;
5576
5577 for_each_class(class) {
5578 if (class->rq_offline)
5579 class->rq_offline(rq);
5580 }
5581
c6c4927b 5582 cpumask_clear_cpu(rq->cpu, rq->rd->online);
1f11eb6a
GH
5583 rq->online = 0;
5584 }
5585}
5586
9cf7243d 5587static void set_cpu_rq_start_time(unsigned int cpu)
1da177e4 5588{
969c7921 5589 struct rq *rq = cpu_rq(cpu);
1da177e4 5590
a803f026
CM
5591 rq->age_stamp = sched_clock_cpu(cpu);
5592}
5593
d1ccc66d
IM
5594/*
5595 * used to mark begin/end of suspend/resume:
5596 */
5597static int num_cpus_frozen;
d35be8ba 5598
1da177e4 5599/*
3a101d05
TH
5600 * Update cpusets according to cpu_active mask. If cpusets are
5601 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5602 * around partition_sched_domains().
d35be8ba
SB
5603 *
5604 * If we come here as part of a suspend/resume, don't touch cpusets because we
5605 * want to restore it back to its original state upon resume anyway.
1da177e4 5606 */
40190a78 5607static void cpuset_cpu_active(void)
e761b772 5608{
40190a78 5609 if (cpuhp_tasks_frozen) {
d35be8ba
SB
5610 /*
5611 * num_cpus_frozen tracks how many CPUs are involved in suspend
5612 * resume sequence. As long as this is not the last online
5613 * operation in the resume sequence, just build a single sched
5614 * domain, ignoring cpusets.
5615 */
50e76632
PZ
5616 partition_sched_domains(1, NULL, NULL);
5617 if (--num_cpus_frozen)
135fb3e1 5618 return;
d35be8ba
SB
5619 /*
5620 * This is the last CPU online operation. So fall through and
5621 * restore the original sched domains by considering the
5622 * cpuset configurations.
5623 */
50e76632 5624 cpuset_force_rebuild();
3a101d05 5625 }
30e03acd 5626 cpuset_update_active_cpus();
3a101d05 5627}
e761b772 5628
40190a78 5629static int cpuset_cpu_inactive(unsigned int cpu)
3a101d05 5630{
40190a78 5631 if (!cpuhp_tasks_frozen) {
06a76fe0 5632 if (dl_cpu_busy(cpu))
135fb3e1 5633 return -EBUSY;
30e03acd 5634 cpuset_update_active_cpus();
135fb3e1 5635 } else {
d35be8ba
SB
5636 num_cpus_frozen++;
5637 partition_sched_domains(1, NULL, NULL);
e761b772 5638 }
135fb3e1 5639 return 0;
e761b772 5640}
e761b772 5641
40190a78 5642int sched_cpu_activate(unsigned int cpu)
135fb3e1 5643{
7d976699 5644 struct rq *rq = cpu_rq(cpu);
8a8c69c3 5645 struct rq_flags rf;
7d976699 5646
53d195f2
PZ
5647#ifdef CONFIG_SCHED_SMT
5648 /*
5649 * The sched_smt_present static key needs to be evaluated on every
5650 * hotplug event because at boot time SMT might be disabled when
5651 * the number of booted CPUs is limited.
5652 *
5653 * If then later a sibling gets hotplugged, then the key would stay
5654 * off and SMT scheduling would never be functional.
5655 */
5656 if (cpumask_weight(cpu_smt_mask(cpu)) > 1)
5657 static_branch_enable_cpuslocked(&sched_smt_present);
5658#endif
40190a78 5659 set_cpu_active(cpu, true);
135fb3e1 5660
40190a78 5661 if (sched_smp_initialized) {
135fb3e1 5662 sched_domains_numa_masks_set(cpu);
40190a78 5663 cpuset_cpu_active();
e761b772 5664 }
7d976699
TG
5665
5666 /*
5667 * Put the rq online, if not already. This happens:
5668 *
5669 * 1) In the early boot process, because we build the real domains
d1ccc66d 5670 * after all CPUs have been brought up.
7d976699
TG
5671 *
5672 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5673 * domains.
5674 */
8a8c69c3 5675 rq_lock_irqsave(rq, &rf);
7d976699
TG
5676 if (rq->rd) {
5677 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5678 set_rq_online(rq);
5679 }
8a8c69c3 5680 rq_unlock_irqrestore(rq, &rf);
7d976699
TG
5681
5682 update_max_interval();
5683
40190a78 5684 return 0;
135fb3e1
TG
5685}
5686
40190a78 5687int sched_cpu_deactivate(unsigned int cpu)
135fb3e1 5688{
135fb3e1
TG
5689 int ret;
5690
40190a78 5691 set_cpu_active(cpu, false);
b2454caa
PZ
5692 /*
5693 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5694 * users of this state to go away such that all new such users will
5695 * observe it.
5696 *
b2454caa
PZ
5697 * Do sync before park smpboot threads to take care the rcu boost case.
5698 */
d7d34d5e 5699 synchronize_rcu_mult(call_rcu, call_rcu_sched);
40190a78
TG
5700
5701 if (!sched_smp_initialized)
5702 return 0;
5703
5704 ret = cpuset_cpu_inactive(cpu);
5705 if (ret) {
5706 set_cpu_active(cpu, true);
5707 return ret;
135fb3e1 5708 }
40190a78
TG
5709 sched_domains_numa_masks_clear(cpu);
5710 return 0;
135fb3e1
TG
5711}
5712
94baf7a5
TG
5713static void sched_rq_cpu_starting(unsigned int cpu)
5714{
5715 struct rq *rq = cpu_rq(cpu);
5716
5717 rq->calc_load_update = calc_load_update;
94baf7a5
TG
5718 update_max_interval();
5719}
5720
135fb3e1
TG
5721int sched_cpu_starting(unsigned int cpu)
5722{
5723 set_cpu_rq_start_time(cpu);
94baf7a5 5724 sched_rq_cpu_starting(cpu);
135fb3e1 5725 return 0;
e761b772 5726}
e761b772 5727
f2785ddb
TG
5728#ifdef CONFIG_HOTPLUG_CPU
5729int sched_cpu_dying(unsigned int cpu)
5730{
5731 struct rq *rq = cpu_rq(cpu);
8a8c69c3 5732 struct rq_flags rf;
f2785ddb
TG
5733
5734 /* Handle pending wakeups and then migrate everything off */
5735 sched_ttwu_pending();
8a8c69c3
PZ
5736
5737 rq_lock_irqsave(rq, &rf);
f2785ddb
TG
5738 if (rq->rd) {
5739 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5740 set_rq_offline(rq);
5741 }
8a8c69c3 5742 migrate_tasks(rq, &rf);
f2785ddb 5743 BUG_ON(rq->nr_running != 1);
8a8c69c3
PZ
5744 rq_unlock_irqrestore(rq, &rf);
5745
f2785ddb
TG
5746 calc_load_migrate(rq);
5747 update_max_interval();
20a5c8cc 5748 nohz_balance_exit_idle(cpu);
e5ef27d0 5749 hrtick_clear(rq);
f2785ddb
TG
5750 return 0;
5751}
5752#endif
5753
1da177e4
LT
5754void __init sched_init_smp(void)
5755{
cb83b629
PZ
5756 sched_init_numa();
5757
6acce3ef
PZ
5758 /*
5759 * There's no userspace yet to cause hotplug operations; hence all the
d1ccc66d 5760 * CPU masks are stable and all blatant races in the below code cannot
6acce3ef
PZ
5761 * happen.
5762 */
712555ee 5763 mutex_lock(&sched_domains_mutex);
8d5dc512 5764 sched_init_domains(cpu_active_mask);
712555ee 5765 mutex_unlock(&sched_domains_mutex);
e761b772 5766
5c1e1767 5767 /* Move init over to a non-isolated CPU */
edb93821 5768 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5c1e1767 5769 BUG();
19978ca6 5770 sched_init_granularity();
4212823f 5771
0e3900e6 5772 init_sched_rt_class();
1baca4ce 5773 init_sched_dl_class();
1b568f0a 5774
e26fbffd 5775 sched_smp_initialized = true;
1da177e4 5776}
e26fbffd
TG
5777
5778static int __init migration_init(void)
5779{
94baf7a5 5780 sched_rq_cpu_starting(smp_processor_id());
e26fbffd 5781 return 0;
1da177e4 5782}
e26fbffd
TG
5783early_initcall(migration_init);
5784
1da177e4
LT
5785#else
5786void __init sched_init_smp(void)
5787{
19978ca6 5788 sched_init_granularity();
1da177e4
LT
5789}
5790#endif /* CONFIG_SMP */
5791
5792int in_sched_functions(unsigned long addr)
5793{
1da177e4
LT
5794 return in_lock_functions(addr) ||
5795 (addr >= (unsigned long)__sched_text_start
5796 && addr < (unsigned long)__sched_text_end);
5797}
5798
029632fb 5799#ifdef CONFIG_CGROUP_SCHED
27b4b931
LZ
5800/*
5801 * Default task group.
5802 * Every task in system belongs to this group at bootup.
5803 */
029632fb 5804struct task_group root_task_group;
35cf4e50 5805LIST_HEAD(task_groups);
b0367629
WL
5806
5807/* Cacheline aligned slab cache for task_group */
5808static struct kmem_cache *task_group_cache __read_mostly;
052f1dc7 5809#endif
6f505b16 5810
e6252c3e 5811DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
10e2f1ac 5812DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
6f505b16 5813
1da177e4
LT
5814void __init sched_init(void)
5815{
dd41f596 5816 int i, j;
434d53b0
MT
5817 unsigned long alloc_size = 0, ptr;
5818
9881b024 5819 sched_clock_init();
5822a454 5820 wait_bit_init();
9dcb8b68 5821
434d53b0
MT
5822#ifdef CONFIG_FAIR_GROUP_SCHED
5823 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5824#endif
5825#ifdef CONFIG_RT_GROUP_SCHED
5826 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5827#endif
434d53b0 5828 if (alloc_size) {
36b7b6d4 5829 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
434d53b0
MT
5830
5831#ifdef CONFIG_FAIR_GROUP_SCHED
07e06b01 5832 root_task_group.se = (struct sched_entity **)ptr;
434d53b0
MT
5833 ptr += nr_cpu_ids * sizeof(void **);
5834
07e06b01 5835 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
434d53b0 5836 ptr += nr_cpu_ids * sizeof(void **);
eff766a6 5837
6d6bc0ad 5838#endif /* CONFIG_FAIR_GROUP_SCHED */
434d53b0 5839#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 5840 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
434d53b0
MT
5841 ptr += nr_cpu_ids * sizeof(void **);
5842
07e06b01 5843 root_task_group.rt_rq = (struct rt_rq **)ptr;
eff766a6
PZ
5844 ptr += nr_cpu_ids * sizeof(void **);
5845
6d6bc0ad 5846#endif /* CONFIG_RT_GROUP_SCHED */
b74e6278 5847 }
df7c8e84 5848#ifdef CONFIG_CPUMASK_OFFSTACK
b74e6278
AT
5849 for_each_possible_cpu(i) {
5850 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
5851 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
10e2f1ac
PZ
5852 per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
5853 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
434d53b0 5854 }
b74e6278 5855#endif /* CONFIG_CPUMASK_OFFSTACK */
dd41f596 5856
d1ccc66d
IM
5857 init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
5858 init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
332ac17e 5859
57d885fe
GH
5860#ifdef CONFIG_SMP
5861 init_defrootdomain();
5862#endif
5863
d0b27fa7 5864#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 5865 init_rt_bandwidth(&root_task_group.rt_bandwidth,
d0b27fa7 5866 global_rt_period(), global_rt_runtime());
6d6bc0ad 5867#endif /* CONFIG_RT_GROUP_SCHED */
d0b27fa7 5868
7c941438 5869#ifdef CONFIG_CGROUP_SCHED
b0367629
WL
5870 task_group_cache = KMEM_CACHE(task_group, 0);
5871
07e06b01
YZ
5872 list_add(&root_task_group.list, &task_groups);
5873 INIT_LIST_HEAD(&root_task_group.children);
f4d6f6c2 5874 INIT_LIST_HEAD(&root_task_group.siblings);
5091faa4 5875 autogroup_init(&init_task);
7c941438 5876#endif /* CONFIG_CGROUP_SCHED */
6f505b16 5877
0a945022 5878 for_each_possible_cpu(i) {
70b97a7f 5879 struct rq *rq;
1da177e4
LT
5880
5881 rq = cpu_rq(i);
05fa785c 5882 raw_spin_lock_init(&rq->lock);
7897986b 5883 rq->nr_running = 0;
dce48a84
TG
5884 rq->calc_load_active = 0;
5885 rq->calc_load_update = jiffies + LOAD_FREQ;
acb5a9ba 5886 init_cfs_rq(&rq->cfs);
07c54f7a
AV
5887 init_rt_rq(&rq->rt);
5888 init_dl_rq(&rq->dl);
dd41f596 5889#ifdef CONFIG_FAIR_GROUP_SCHED
029632fb 5890 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6f505b16 5891 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
9c2791f9 5892 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
354d60c2 5893 /*
d1ccc66d 5894 * How much CPU bandwidth does root_task_group get?
354d60c2
DG
5895 *
5896 * In case of task-groups formed thr' the cgroup filesystem, it
d1ccc66d
IM
5897 * gets 100% of the CPU resources in the system. This overall
5898 * system CPU resource is divided among the tasks of
07e06b01 5899 * root_task_group and its child task-groups in a fair manner,
354d60c2
DG
5900 * based on each entity's (task or task-group's) weight
5901 * (se->load.weight).
5902 *
07e06b01 5903 * In other words, if root_task_group has 10 tasks of weight
354d60c2 5904 * 1024) and two child groups A0 and A1 (of weight 1024 each),
d1ccc66d 5905 * then A0's share of the CPU resource is:
354d60c2 5906 *
0d905bca 5907 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
354d60c2 5908 *
07e06b01
YZ
5909 * We achieve this by letting root_task_group's tasks sit
5910 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
354d60c2 5911 */
ab84d31e 5912 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
07e06b01 5913 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
354d60c2
DG
5914#endif /* CONFIG_FAIR_GROUP_SCHED */
5915
5916 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
052f1dc7 5917#ifdef CONFIG_RT_GROUP_SCHED
07e06b01 5918 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
dd41f596 5919#endif
1da177e4 5920
dd41f596
IM
5921 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
5922 rq->cpu_load[j] = 0;
fdf3e95d 5923
1da177e4 5924#ifdef CONFIG_SMP
41c7ce9a 5925 rq->sd = NULL;
57d885fe 5926 rq->rd = NULL;
ca6d75e6 5927 rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
e3fca9e7 5928 rq->balance_callback = NULL;
1da177e4 5929 rq->active_balance = 0;
dd41f596 5930 rq->next_balance = jiffies;
1da177e4 5931 rq->push_cpu = 0;
0a2966b4 5932 rq->cpu = i;
1f11eb6a 5933 rq->online = 0;
eae0c9df
MG
5934 rq->idle_stamp = 0;
5935 rq->avg_idle = 2*sysctl_sched_migration_cost;
9bd721c5 5936 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
367456c7
PZ
5937
5938 INIT_LIST_HEAD(&rq->cfs_tasks);
5939
dc938520 5940 rq_attach_root(rq, &def_root_domain);
3451d024 5941#ifdef CONFIG_NO_HZ_COMMON
9fd81dd5 5942 rq->last_load_update_tick = jiffies;
1c792db7 5943 rq->nohz_flags = 0;
83cd4fe2 5944#endif
265f22a9
FW
5945#ifdef CONFIG_NO_HZ_FULL
5946 rq->last_sched_tick = 0;
5947#endif
9fd81dd5 5948#endif /* CONFIG_SMP */
8f4d37ec 5949 init_rq_hrtick(rq);
1da177e4 5950 atomic_set(&rq->nr_iowait, 0);
1da177e4
LT
5951 }
5952
9059393e 5953 set_load_weight(&init_task, false);
b50f60ce 5954
1da177e4
LT
5955 /*
5956 * The boot idle thread does lazy MMU switching as well:
5957 */
f1f10076 5958 mmgrab(&init_mm);
1da177e4
LT
5959 enter_lazy_tlb(&init_mm, current);
5960
5961 /*
5962 * Make us the idle thread. Technically, schedule() should not be
5963 * called from this thread, however somewhere below it might be,
5964 * but because we are the idle thread, we just pick up running again
5965 * when this runqueue becomes "idle".
5966 */
5967 init_idle(current, smp_processor_id());
dce48a84
TG
5968
5969 calc_load_update = jiffies + LOAD_FREQ;
5970
bf4d83f6 5971#ifdef CONFIG_SMP
29d5e047 5972 idle_thread_set_boot_cpu();
9cf7243d 5973 set_cpu_rq_start_time(smp_processor_id());
029632fb
PZ
5974#endif
5975 init_sched_fair_class();
6a7b3dc3 5976
4698f88c
JP
5977 init_schedstats();
5978
6892b75e 5979 scheduler_running = 1;
1da177e4
LT
5980}
5981
d902db1e 5982#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
e4aafea2
FW
5983static inline int preempt_count_equals(int preempt_offset)
5984{
da7142e2 5985 int nested = preempt_count() + rcu_preempt_depth();
e4aafea2 5986
4ba8216c 5987 return (nested == preempt_offset);
e4aafea2
FW
5988}
5989
d894837f 5990void __might_sleep(const char *file, int line, int preempt_offset)
1da177e4 5991{
8eb23b9f
PZ
5992 /*
5993 * Blocking primitives will set (and therefore destroy) current->state,
5994 * since we will exit with TASK_RUNNING make sure we enter with it,
5995 * otherwise we will destroy state.
5996 */
00845eb9 5997 WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
8eb23b9f
PZ
5998 "do not call blocking ops when !TASK_RUNNING; "
5999 "state=%lx set at [<%p>] %pS\n",
6000 current->state,
6001 (void *)current->task_state_change,
00845eb9 6002 (void *)current->task_state_change);
8eb23b9f 6003
3427445a
PZ
6004 ___might_sleep(file, line, preempt_offset);
6005}
6006EXPORT_SYMBOL(__might_sleep);
6007
6008void ___might_sleep(const char *file, int line, int preempt_offset)
1da177e4 6009{
d1ccc66d
IM
6010 /* Ratelimiting timestamp: */
6011 static unsigned long prev_jiffy;
6012
d1c6d149 6013 unsigned long preempt_disable_ip;
1da177e4 6014
d1ccc66d
IM
6015 /* WARN_ON_ONCE() by default, no rate limit required: */
6016 rcu_sleep_check();
6017
db273be2
TG
6018 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6019 !is_idle_task(current)) ||
1c3c5eab
TG
6020 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
6021 oops_in_progress)
aef745fc 6022 return;
1c3c5eab 6023
aef745fc
IM
6024 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6025 return;
6026 prev_jiffy = jiffies;
6027
d1ccc66d 6028 /* Save this before calling printk(), since that will clobber it: */
d1c6d149
VN
6029 preempt_disable_ip = get_preempt_disable_ip(current);
6030
3df0fc5b
PZ
6031 printk(KERN_ERR
6032 "BUG: sleeping function called from invalid context at %s:%d\n",
6033 file, line);
6034 printk(KERN_ERR
6035 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6036 in_atomic(), irqs_disabled(),
6037 current->pid, current->comm);
aef745fc 6038
a8b686b3
ES
6039 if (task_stack_end_corrupted(current))
6040 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6041
aef745fc
IM
6042 debug_show_held_locks(current);
6043 if (irqs_disabled())
6044 print_irqtrace_events(current);
d1c6d149
VN
6045 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6046 && !preempt_count_equals(preempt_offset)) {
8f47b187 6047 pr_err("Preemption disabled at:");
d1c6d149 6048 print_ip_sym(preempt_disable_ip);
8f47b187
TG
6049 pr_cont("\n");
6050 }
aef745fc 6051 dump_stack();
f0b22e39 6052 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
1da177e4 6053}
3427445a 6054EXPORT_SYMBOL(___might_sleep);
1da177e4
LT
6055#endif
6056
6057#ifdef CONFIG_MAGIC_SYSRQ
dbc7f069 6058void normalize_rt_tasks(void)
3a5e4dc1 6059{
dbc7f069 6060 struct task_struct *g, *p;
d50dde5a
DF
6061 struct sched_attr attr = {
6062 .sched_policy = SCHED_NORMAL,
6063 };
1da177e4 6064
3472eaa1 6065 read_lock(&tasklist_lock);
5d07f420 6066 for_each_process_thread(g, p) {
178be793
IM
6067 /*
6068 * Only normalize user tasks:
6069 */
3472eaa1 6070 if (p->flags & PF_KTHREAD)
178be793
IM
6071 continue;
6072
4fa8d299
JP
6073 p->se.exec_start = 0;
6074 schedstat_set(p->se.statistics.wait_start, 0);
6075 schedstat_set(p->se.statistics.sleep_start, 0);
6076 schedstat_set(p->se.statistics.block_start, 0);
dd41f596 6077
aab03e05 6078 if (!dl_task(p) && !rt_task(p)) {
dd41f596
IM
6079 /*
6080 * Renice negative nice level userspace
6081 * tasks back to 0:
6082 */
3472eaa1 6083 if (task_nice(p) < 0)
dd41f596 6084 set_user_nice(p, 0);
1da177e4 6085 continue;
dd41f596 6086 }
1da177e4 6087
dbc7f069 6088 __sched_setscheduler(p, &attr, false, false);
5d07f420 6089 }
3472eaa1 6090 read_unlock(&tasklist_lock);
1da177e4
LT
6091}
6092
6093#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a 6094
67fc4e0c 6095#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
1df5c10a 6096/*
67fc4e0c 6097 * These functions are only useful for the IA64 MCA handling, or kdb.
1df5c10a
LT
6098 *
6099 * They can only be called when the whole system has been
6100 * stopped - every CPU needs to be quiescent, and no scheduling
6101 * activity can take place. Using them for anything else would
6102 * be a serious bug, and as a result, they aren't even visible
6103 * under any other configuration.
6104 */
6105
6106/**
d1ccc66d 6107 * curr_task - return the current task for a given CPU.
1df5c10a
LT
6108 * @cpu: the processor in question.
6109 *
6110 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
e69f6186
YB
6111 *
6112 * Return: The current task for @cpu.
1df5c10a 6113 */
36c8b586 6114struct task_struct *curr_task(int cpu)
1df5c10a
LT
6115{
6116 return cpu_curr(cpu);
6117}
6118
67fc4e0c
JW
6119#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6120
6121#ifdef CONFIG_IA64
1df5c10a 6122/**
d1ccc66d 6123 * set_curr_task - set the current task for a given CPU.
1df5c10a
LT
6124 * @cpu: the processor in question.
6125 * @p: the task pointer to set.
6126 *
6127 * Description: This function must only be used when non-maskable interrupts
41a2d6cf 6128 * are serviced on a separate stack. It allows the architecture to switch the
d1ccc66d 6129 * notion of the current task on a CPU in a non-blocking manner. This function
1df5c10a
LT
6130 * must be called with all CPU's synchronized, and interrupts disabled, the
6131 * and caller must save the original value of the current task (see
6132 * curr_task() above) and restore that value before reenabling interrupts and
6133 * re-starting the system.
6134 *
6135 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6136 */
a458ae2e 6137void ia64_set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
6138{
6139 cpu_curr(cpu) = p;
6140}
6141
6142#endif
29f59db3 6143
7c941438 6144#ifdef CONFIG_CGROUP_SCHED
029632fb
PZ
6145/* task_group_lock serializes the addition/removal of task groups */
6146static DEFINE_SPINLOCK(task_group_lock);
6147
2f5177f0 6148static void sched_free_group(struct task_group *tg)
bccbe08a
PZ
6149{
6150 free_fair_sched_group(tg);
6151 free_rt_sched_group(tg);
e9aa1dd1 6152 autogroup_free(tg);
b0367629 6153 kmem_cache_free(task_group_cache, tg);
bccbe08a
PZ
6154}
6155
6156/* allocate runqueue etc for a new task group */
ec7dc8ac 6157struct task_group *sched_create_group(struct task_group *parent)
bccbe08a
PZ
6158{
6159 struct task_group *tg;
bccbe08a 6160
b0367629 6161 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
bccbe08a
PZ
6162 if (!tg)
6163 return ERR_PTR(-ENOMEM);
6164
ec7dc8ac 6165 if (!alloc_fair_sched_group(tg, parent))
bccbe08a
PZ
6166 goto err;
6167
ec7dc8ac 6168 if (!alloc_rt_sched_group(tg, parent))
bccbe08a
PZ
6169 goto err;
6170
ace783b9
LZ
6171 return tg;
6172
6173err:
2f5177f0 6174 sched_free_group(tg);
ace783b9
LZ
6175 return ERR_PTR(-ENOMEM);
6176}
6177
6178void sched_online_group(struct task_group *tg, struct task_group *parent)
6179{
6180 unsigned long flags;
6181
8ed36996 6182 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 6183 list_add_rcu(&tg->list, &task_groups);
f473aa5e 6184
d1ccc66d
IM
6185 /* Root should already exist: */
6186 WARN_ON(!parent);
f473aa5e
PZ
6187
6188 tg->parent = parent;
f473aa5e 6189 INIT_LIST_HEAD(&tg->children);
09f2724a 6190 list_add_rcu(&tg->siblings, &parent->children);
8ed36996 6191 spin_unlock_irqrestore(&task_group_lock, flags);
8663e24d
PZ
6192
6193 online_fair_sched_group(tg);
29f59db3
SV
6194}
6195
9b5b7751 6196/* rcu callback to free various structures associated with a task group */
2f5177f0 6197static void sched_free_group_rcu(struct rcu_head *rhp)
29f59db3 6198{
d1ccc66d 6199 /* Now it should be safe to free those cfs_rqs: */
2f5177f0 6200 sched_free_group(container_of(rhp, struct task_group, rcu));
29f59db3
SV
6201}
6202
4cf86d77 6203void sched_destroy_group(struct task_group *tg)
ace783b9 6204{
d1ccc66d 6205 /* Wait for possible concurrent references to cfs_rqs complete: */
2f5177f0 6206 call_rcu(&tg->rcu, sched_free_group_rcu);
ace783b9
LZ
6207}
6208
6209void sched_offline_group(struct task_group *tg)
29f59db3 6210{
8ed36996 6211 unsigned long flags;
29f59db3 6212
d1ccc66d 6213 /* End participation in shares distribution: */
6fe1f348 6214 unregister_fair_sched_group(tg);
3d4b47b4
PZ
6215
6216 spin_lock_irqsave(&task_group_lock, flags);
6f505b16 6217 list_del_rcu(&tg->list);
f473aa5e 6218 list_del_rcu(&tg->siblings);
8ed36996 6219 spin_unlock_irqrestore(&task_group_lock, flags);
29f59db3
SV
6220}
6221
ea86cb4b 6222static void sched_change_group(struct task_struct *tsk, int type)
29f59db3 6223{
8323f26c 6224 struct task_group *tg;
29f59db3 6225
f7b8a47d
KT
6226 /*
6227 * All callers are synchronized by task_rq_lock(); we do not use RCU
6228 * which is pointless here. Thus, we pass "true" to task_css_check()
6229 * to prevent lockdep warnings.
6230 */
6231 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8323f26c
PZ
6232 struct task_group, css);
6233 tg = autogroup_task_group(tsk, tg);
6234 tsk->sched_task_group = tg;
6235
810b3817 6236#ifdef CONFIG_FAIR_GROUP_SCHED
ea86cb4b
VG
6237 if (tsk->sched_class->task_change_group)
6238 tsk->sched_class->task_change_group(tsk, type);
b2b5ce02 6239 else
810b3817 6240#endif
b2b5ce02 6241 set_task_rq(tsk, task_cpu(tsk));
ea86cb4b
VG
6242}
6243
6244/*
6245 * Change task's runqueue when it moves between groups.
6246 *
6247 * The caller of this function should have put the task in its new group by
6248 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6249 * its new group.
6250 */
6251void sched_move_task(struct task_struct *tsk)
6252{
7a57f32a
PZ
6253 int queued, running, queue_flags =
6254 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
ea86cb4b
VG
6255 struct rq_flags rf;
6256 struct rq *rq;
6257
6258 rq = task_rq_lock(tsk, &rf);
1b1d6225 6259 update_rq_clock(rq);
ea86cb4b
VG
6260
6261 running = task_current(rq, tsk);
6262 queued = task_on_rq_queued(tsk);
6263
6264 if (queued)
7a57f32a 6265 dequeue_task(rq, tsk, queue_flags);
bb3bac2c 6266 if (running)
ea86cb4b
VG
6267 put_prev_task(rq, tsk);
6268
6269 sched_change_group(tsk, TASK_MOVE_GROUP);
810b3817 6270
da0c1e65 6271 if (queued)
7a57f32a 6272 enqueue_task(rq, tsk, queue_flags);
bb3bac2c 6273 if (running)
b2bf6c31 6274 set_curr_task(rq, tsk);
29f59db3 6275
eb580751 6276 task_rq_unlock(rq, tsk, &rf);
29f59db3 6277}
68318b8e 6278
a7c6d554 6279static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
68318b8e 6280{
a7c6d554 6281 return css ? container_of(css, struct task_group, css) : NULL;
68318b8e
SV
6282}
6283
eb95419b
TH
6284static struct cgroup_subsys_state *
6285cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
68318b8e 6286{
eb95419b
TH
6287 struct task_group *parent = css_tg(parent_css);
6288 struct task_group *tg;
68318b8e 6289
eb95419b 6290 if (!parent) {
68318b8e 6291 /* This is early initialization for the top cgroup */
07e06b01 6292 return &root_task_group.css;
68318b8e
SV
6293 }
6294
ec7dc8ac 6295 tg = sched_create_group(parent);
68318b8e
SV
6296 if (IS_ERR(tg))
6297 return ERR_PTR(-ENOMEM);
6298
68318b8e
SV
6299 return &tg->css;
6300}
6301
96b77745
KK
6302/* Expose task group only after completing cgroup initialization */
6303static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6304{
6305 struct task_group *tg = css_tg(css);
6306 struct task_group *parent = css_tg(css->parent);
6307
6308 if (parent)
6309 sched_online_group(tg, parent);
6310 return 0;
6311}
6312
2f5177f0 6313static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
ace783b9 6314{
eb95419b 6315 struct task_group *tg = css_tg(css);
ace783b9 6316
2f5177f0 6317 sched_offline_group(tg);
ace783b9
LZ
6318}
6319
eb95419b 6320static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
68318b8e 6321{
eb95419b 6322 struct task_group *tg = css_tg(css);
68318b8e 6323
2f5177f0
PZ
6324 /*
6325 * Relies on the RCU grace period between css_released() and this.
6326 */
6327 sched_free_group(tg);
ace783b9
LZ
6328}
6329
ea86cb4b
VG
6330/*
6331 * This is called before wake_up_new_task(), therefore we really only
6332 * have to set its group bits, all the other stuff does not apply.
6333 */
b53202e6 6334static void cpu_cgroup_fork(struct task_struct *task)
eeb61e53 6335{
ea86cb4b
VG
6336 struct rq_flags rf;
6337 struct rq *rq;
6338
6339 rq = task_rq_lock(task, &rf);
6340
80f5c1b8 6341 update_rq_clock(rq);
ea86cb4b
VG
6342 sched_change_group(task, TASK_SET_GROUP);
6343
6344 task_rq_unlock(rq, task, &rf);
eeb61e53
KT
6345}
6346
1f7dd3e5 6347static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
68318b8e 6348{
bb9d97b6 6349 struct task_struct *task;
1f7dd3e5 6350 struct cgroup_subsys_state *css;
7dc603c9 6351 int ret = 0;
bb9d97b6 6352
1f7dd3e5 6353 cgroup_taskset_for_each(task, css, tset) {
b68aa230 6354#ifdef CONFIG_RT_GROUP_SCHED
eb95419b 6355 if (!sched_rt_can_attach(css_tg(css), task))
bb9d97b6 6356 return -EINVAL;
b68aa230 6357#else
bb9d97b6
TH
6358 /* We don't support RT-tasks being in separate groups */
6359 if (task->sched_class != &fair_sched_class)
6360 return -EINVAL;
b68aa230 6361#endif
7dc603c9
PZ
6362 /*
6363 * Serialize against wake_up_new_task() such that if its
6364 * running, we're sure to observe its full state.
6365 */
6366 raw_spin_lock_irq(&task->pi_lock);
6367 /*
6368 * Avoid calling sched_move_task() before wake_up_new_task()
6369 * has happened. This would lead to problems with PELT, due to
6370 * move wanting to detach+attach while we're not attached yet.
6371 */
6372 if (task->state == TASK_NEW)
6373 ret = -EINVAL;
6374 raw_spin_unlock_irq(&task->pi_lock);
6375
6376 if (ret)
6377 break;
bb9d97b6 6378 }
7dc603c9 6379 return ret;
be367d09 6380}
68318b8e 6381
1f7dd3e5 6382static void cpu_cgroup_attach(struct cgroup_taskset *tset)
68318b8e 6383{
bb9d97b6 6384 struct task_struct *task;
1f7dd3e5 6385 struct cgroup_subsys_state *css;
bb9d97b6 6386
1f7dd3e5 6387 cgroup_taskset_for_each(task, css, tset)
bb9d97b6 6388 sched_move_task(task);
68318b8e
SV
6389}
6390
052f1dc7 6391#ifdef CONFIG_FAIR_GROUP_SCHED
182446d0
TH
6392static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6393 struct cftype *cftype, u64 shareval)
68318b8e 6394{
182446d0 6395 return sched_group_set_shares(css_tg(css), scale_load(shareval));
68318b8e
SV
6396}
6397
182446d0
TH
6398static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6399 struct cftype *cft)
68318b8e 6400{
182446d0 6401 struct task_group *tg = css_tg(css);
68318b8e 6402
c8b28116 6403 return (u64) scale_load_down(tg->shares);
68318b8e 6404}
ab84d31e
PT
6405
6406#ifdef CONFIG_CFS_BANDWIDTH
a790de99
PT
6407static DEFINE_MUTEX(cfs_constraints_mutex);
6408
ab84d31e
PT
6409const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6410const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6411
a790de99
PT
6412static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6413
ab84d31e
PT
6414static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6415{
56f570e5 6416 int i, ret = 0, runtime_enabled, runtime_was_enabled;
029632fb 6417 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
ab84d31e
PT
6418
6419 if (tg == &root_task_group)
6420 return -EINVAL;
6421
6422 /*
6423 * Ensure we have at some amount of bandwidth every period. This is
6424 * to prevent reaching a state of large arrears when throttled via
6425 * entity_tick() resulting in prolonged exit starvation.
6426 */
6427 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6428 return -EINVAL;
6429
6430 /*
6431 * Likewise, bound things on the otherside by preventing insane quota
6432 * periods. This also allows us to normalize in computing quota
6433 * feasibility.
6434 */
6435 if (period > max_cfs_quota_period)
6436 return -EINVAL;
6437
0e59bdae
KT
6438 /*
6439 * Prevent race between setting of cfs_rq->runtime_enabled and
6440 * unthrottle_offline_cfs_rqs().
6441 */
6442 get_online_cpus();
a790de99
PT
6443 mutex_lock(&cfs_constraints_mutex);
6444 ret = __cfs_schedulable(tg, period, quota);
6445 if (ret)
6446 goto out_unlock;
6447
58088ad0 6448 runtime_enabled = quota != RUNTIME_INF;
56f570e5 6449 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
1ee14e6c
BS
6450 /*
6451 * If we need to toggle cfs_bandwidth_used, off->on must occur
6452 * before making related changes, and on->off must occur afterwards
6453 */
6454 if (runtime_enabled && !runtime_was_enabled)
6455 cfs_bandwidth_usage_inc();
ab84d31e
PT
6456 raw_spin_lock_irq(&cfs_b->lock);
6457 cfs_b->period = ns_to_ktime(period);
6458 cfs_b->quota = quota;
58088ad0 6459
a9cf55b2 6460 __refill_cfs_bandwidth_runtime(cfs_b);
d1ccc66d
IM
6461
6462 /* Restart the period timer (if active) to handle new period expiry: */
77a4d1a1
PZ
6463 if (runtime_enabled)
6464 start_cfs_bandwidth(cfs_b);
d1ccc66d 6465
ab84d31e
PT
6466 raw_spin_unlock_irq(&cfs_b->lock);
6467
0e59bdae 6468 for_each_online_cpu(i) {
ab84d31e 6469 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
029632fb 6470 struct rq *rq = cfs_rq->rq;
8a8c69c3 6471 struct rq_flags rf;
ab84d31e 6472
8a8c69c3 6473 rq_lock_irq(rq, &rf);
58088ad0 6474 cfs_rq->runtime_enabled = runtime_enabled;
ab84d31e 6475 cfs_rq->runtime_remaining = 0;
671fd9da 6476
029632fb 6477 if (cfs_rq->throttled)
671fd9da 6478 unthrottle_cfs_rq(cfs_rq);
8a8c69c3 6479 rq_unlock_irq(rq, &rf);
ab84d31e 6480 }
1ee14e6c
BS
6481 if (runtime_was_enabled && !runtime_enabled)
6482 cfs_bandwidth_usage_dec();
a790de99
PT
6483out_unlock:
6484 mutex_unlock(&cfs_constraints_mutex);
0e59bdae 6485 put_online_cpus();
ab84d31e 6486
a790de99 6487 return ret;
ab84d31e
PT
6488}
6489
6490int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
6491{
6492 u64 quota, period;
6493
029632fb 6494 period = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
6495 if (cfs_quota_us < 0)
6496 quota = RUNTIME_INF;
6497 else
6498 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
6499
6500 return tg_set_cfs_bandwidth(tg, period, quota);
6501}
6502
6503long tg_get_cfs_quota(struct task_group *tg)
6504{
6505 u64 quota_us;
6506
029632fb 6507 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
ab84d31e
PT
6508 return -1;
6509
029632fb 6510 quota_us = tg->cfs_bandwidth.quota;
ab84d31e
PT
6511 do_div(quota_us, NSEC_PER_USEC);
6512
6513 return quota_us;
6514}
6515
6516int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
6517{
6518 u64 quota, period;
6519
6520 period = (u64)cfs_period_us * NSEC_PER_USEC;
029632fb 6521 quota = tg->cfs_bandwidth.quota;
ab84d31e 6522
ab84d31e
PT
6523 return tg_set_cfs_bandwidth(tg, period, quota);
6524}
6525
6526long tg_get_cfs_period(struct task_group *tg)
6527{
6528 u64 cfs_period_us;
6529
029632fb 6530 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
ab84d31e
PT
6531 do_div(cfs_period_us, NSEC_PER_USEC);
6532
6533 return cfs_period_us;
6534}
6535
182446d0
TH
6536static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
6537 struct cftype *cft)
ab84d31e 6538{
182446d0 6539 return tg_get_cfs_quota(css_tg(css));
ab84d31e
PT
6540}
6541
182446d0
TH
6542static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
6543 struct cftype *cftype, s64 cfs_quota_us)
ab84d31e 6544{
182446d0 6545 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
ab84d31e
PT
6546}
6547
182446d0
TH
6548static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
6549 struct cftype *cft)
ab84d31e 6550{
182446d0 6551 return tg_get_cfs_period(css_tg(css));
ab84d31e
PT
6552}
6553
182446d0
TH
6554static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
6555 struct cftype *cftype, u64 cfs_period_us)
ab84d31e 6556{
182446d0 6557 return tg_set_cfs_period(css_tg(css), cfs_period_us);
ab84d31e
PT
6558}
6559
a790de99
PT
6560struct cfs_schedulable_data {
6561 struct task_group *tg;
6562 u64 period, quota;
6563};
6564
6565/*
6566 * normalize group quota/period to be quota/max_period
6567 * note: units are usecs
6568 */
6569static u64 normalize_cfs_quota(struct task_group *tg,
6570 struct cfs_schedulable_data *d)
6571{
6572 u64 quota, period;
6573
6574 if (tg == d->tg) {
6575 period = d->period;
6576 quota = d->quota;
6577 } else {
6578 period = tg_get_cfs_period(tg);
6579 quota = tg_get_cfs_quota(tg);
6580 }
6581
6582 /* note: these should typically be equivalent */
6583 if (quota == RUNTIME_INF || quota == -1)
6584 return RUNTIME_INF;
6585
6586 return to_ratio(period, quota);
6587}
6588
6589static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
6590{
6591 struct cfs_schedulable_data *d = data;
029632fb 6592 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
a790de99
PT
6593 s64 quota = 0, parent_quota = -1;
6594
6595 if (!tg->parent) {
6596 quota = RUNTIME_INF;
6597 } else {
029632fb 6598 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
a790de99
PT
6599
6600 quota = normalize_cfs_quota(tg, d);
9c58c79a 6601 parent_quota = parent_b->hierarchical_quota;
a790de99
PT
6602
6603 /*
09419522
TH
6604 * Ensure max(child_quota) <= parent_quota. On cgroup2,
6605 * always take the min. On cgroup1, only inherit when no
d1ccc66d 6606 * limit is set:
a790de99 6607 */
09419522
TH
6608 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
6609 quota = min(quota, parent_quota);
6610 } else {
6611 if (quota == RUNTIME_INF)
6612 quota = parent_quota;
6613 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
6614 return -EINVAL;
6615 }
a790de99 6616 }
9c58c79a 6617 cfs_b->hierarchical_quota = quota;
a790de99
PT
6618
6619 return 0;
6620}
6621
6622static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
6623{
8277434e 6624 int ret;
a790de99
PT
6625 struct cfs_schedulable_data data = {
6626 .tg = tg,
6627 .period = period,
6628 .quota = quota,
6629 };
6630
6631 if (quota != RUNTIME_INF) {
6632 do_div(data.period, NSEC_PER_USEC);
6633 do_div(data.quota, NSEC_PER_USEC);
6634 }
6635
8277434e
PT
6636 rcu_read_lock();
6637 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
6638 rcu_read_unlock();
6639
6640 return ret;
a790de99 6641}
e8da1b18 6642
a1f7164c 6643static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
e8da1b18 6644{
2da8ca82 6645 struct task_group *tg = css_tg(seq_css(sf));
029632fb 6646 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
e8da1b18 6647
44ffc75b
TH
6648 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
6649 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
6650 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
e8da1b18
NR
6651
6652 return 0;
6653}
ab84d31e 6654#endif /* CONFIG_CFS_BANDWIDTH */
6d6bc0ad 6655#endif /* CONFIG_FAIR_GROUP_SCHED */
68318b8e 6656
052f1dc7 6657#ifdef CONFIG_RT_GROUP_SCHED
182446d0
TH
6658static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
6659 struct cftype *cft, s64 val)
6f505b16 6660{
182446d0 6661 return sched_group_set_rt_runtime(css_tg(css), val);
6f505b16
PZ
6662}
6663
182446d0
TH
6664static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
6665 struct cftype *cft)
6f505b16 6666{
182446d0 6667 return sched_group_rt_runtime(css_tg(css));
6f505b16 6668}
d0b27fa7 6669
182446d0
TH
6670static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
6671 struct cftype *cftype, u64 rt_period_us)
d0b27fa7 6672{
182446d0 6673 return sched_group_set_rt_period(css_tg(css), rt_period_us);
d0b27fa7
PZ
6674}
6675
182446d0
TH
6676static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
6677 struct cftype *cft)
d0b27fa7 6678{
182446d0 6679 return sched_group_rt_period(css_tg(css));
d0b27fa7 6680}
6d6bc0ad 6681#endif /* CONFIG_RT_GROUP_SCHED */
6f505b16 6682
a1f7164c 6683static struct cftype cpu_legacy_files[] = {
052f1dc7 6684#ifdef CONFIG_FAIR_GROUP_SCHED
fe5c7cc2
PM
6685 {
6686 .name = "shares",
f4c753b7
PM
6687 .read_u64 = cpu_shares_read_u64,
6688 .write_u64 = cpu_shares_write_u64,
fe5c7cc2 6689 },
052f1dc7 6690#endif
ab84d31e
PT
6691#ifdef CONFIG_CFS_BANDWIDTH
6692 {
6693 .name = "cfs_quota_us",
6694 .read_s64 = cpu_cfs_quota_read_s64,
6695 .write_s64 = cpu_cfs_quota_write_s64,
6696 },
6697 {
6698 .name = "cfs_period_us",
6699 .read_u64 = cpu_cfs_period_read_u64,
6700 .write_u64 = cpu_cfs_period_write_u64,
6701 },
e8da1b18
NR
6702 {
6703 .name = "stat",
a1f7164c 6704 .seq_show = cpu_cfs_stat_show,
e8da1b18 6705 },
ab84d31e 6706#endif
052f1dc7 6707#ifdef CONFIG_RT_GROUP_SCHED
6f505b16 6708 {
9f0c1e56 6709 .name = "rt_runtime_us",
06ecb27c
PM
6710 .read_s64 = cpu_rt_runtime_read,
6711 .write_s64 = cpu_rt_runtime_write,
6f505b16 6712 },
d0b27fa7
PZ
6713 {
6714 .name = "rt_period_us",
f4c753b7
PM
6715 .read_u64 = cpu_rt_period_read_uint,
6716 .write_u64 = cpu_rt_period_write_uint,
d0b27fa7 6717 },
052f1dc7 6718#endif
d1ccc66d 6719 { } /* Terminate */
68318b8e
SV
6720};
6721
d41bf8c9
TH
6722static int cpu_extra_stat_show(struct seq_file *sf,
6723 struct cgroup_subsys_state *css)
0d593634 6724{
0d593634
TH
6725#ifdef CONFIG_CFS_BANDWIDTH
6726 {
d41bf8c9 6727 struct task_group *tg = css_tg(css);
0d593634
TH
6728 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6729 u64 throttled_usec;
6730
6731 throttled_usec = cfs_b->throttled_time;
6732 do_div(throttled_usec, NSEC_PER_USEC);
6733
6734 seq_printf(sf, "nr_periods %d\n"
6735 "nr_throttled %d\n"
6736 "throttled_usec %llu\n",
6737 cfs_b->nr_periods, cfs_b->nr_throttled,
6738 throttled_usec);
6739 }
6740#endif
6741 return 0;
6742}
6743
6744#ifdef CONFIG_FAIR_GROUP_SCHED
6745static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
6746 struct cftype *cft)
6747{
6748 struct task_group *tg = css_tg(css);
6749 u64 weight = scale_load_down(tg->shares);
6750
6751 return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
6752}
6753
6754static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
6755 struct cftype *cft, u64 weight)
6756{
6757 /*
6758 * cgroup weight knobs should use the common MIN, DFL and MAX
6759 * values which are 1, 100 and 10000 respectively. While it loses
6760 * a bit of range on both ends, it maps pretty well onto the shares
6761 * value used by scheduler and the round-trip conversions preserve
6762 * the original value over the entire range.
6763 */
6764 if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
6765 return -ERANGE;
6766
6767 weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
6768
6769 return sched_group_set_shares(css_tg(css), scale_load(weight));
6770}
6771
6772static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
6773 struct cftype *cft)
6774{
6775 unsigned long weight = scale_load_down(css_tg(css)->shares);
6776 int last_delta = INT_MAX;
6777 int prio, delta;
6778
6779 /* find the closest nice value to the current weight */
6780 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
6781 delta = abs(sched_prio_to_weight[prio] - weight);
6782 if (delta >= last_delta)
6783 break;
6784 last_delta = delta;
6785 }
6786
6787 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
6788}
6789
6790static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
6791 struct cftype *cft, s64 nice)
6792{
6793 unsigned long weight;
189485aa 6794 int idx;
0d593634
TH
6795
6796 if (nice < MIN_NICE || nice > MAX_NICE)
6797 return -ERANGE;
6798
189485aa
PZ
6799 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
6800 idx = array_index_nospec(idx, 40);
6801 weight = sched_prio_to_weight[idx];
6802
0d593634
TH
6803 return sched_group_set_shares(css_tg(css), scale_load(weight));
6804}
6805#endif
6806
6807static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
6808 long period, long quota)
6809{
6810 if (quota < 0)
6811 seq_puts(sf, "max");
6812 else
6813 seq_printf(sf, "%ld", quota);
6814
6815 seq_printf(sf, " %ld\n", period);
6816}
6817
6818/* caller should put the current value in *@periodp before calling */
6819static int __maybe_unused cpu_period_quota_parse(char *buf,
6820 u64 *periodp, u64 *quotap)
6821{
6822 char tok[21]; /* U64_MAX */
6823
6824 if (!sscanf(buf, "%s %llu", tok, periodp))
6825 return -EINVAL;
6826
6827 *periodp *= NSEC_PER_USEC;
6828
6829 if (sscanf(tok, "%llu", quotap))
6830 *quotap *= NSEC_PER_USEC;
6831 else if (!strcmp(tok, "max"))
6832 *quotap = RUNTIME_INF;
6833 else
6834 return -EINVAL;
6835
6836 return 0;
6837}
6838
6839#ifdef CONFIG_CFS_BANDWIDTH
6840static int cpu_max_show(struct seq_file *sf, void *v)
6841{
6842 struct task_group *tg = css_tg(seq_css(sf));
6843
6844 cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
6845 return 0;
6846}
6847
6848static ssize_t cpu_max_write(struct kernfs_open_file *of,
6849 char *buf, size_t nbytes, loff_t off)
6850{
6851 struct task_group *tg = css_tg(of_css(of));
6852 u64 period = tg_get_cfs_period(tg);
6853 u64 quota;
6854 int ret;
6855
6856 ret = cpu_period_quota_parse(buf, &period, &quota);
6857 if (!ret)
6858 ret = tg_set_cfs_bandwidth(tg, period, quota);
6859 return ret ?: nbytes;
6860}
6861#endif
6862
6863static struct cftype cpu_files[] = {
0d593634
TH
6864#ifdef CONFIG_FAIR_GROUP_SCHED
6865 {
6866 .name = "weight",
6867 .flags = CFTYPE_NOT_ON_ROOT,
6868 .read_u64 = cpu_weight_read_u64,
6869 .write_u64 = cpu_weight_write_u64,
6870 },
6871 {
6872 .name = "weight.nice",
6873 .flags = CFTYPE_NOT_ON_ROOT,
6874 .read_s64 = cpu_weight_nice_read_s64,
6875 .write_s64 = cpu_weight_nice_write_s64,
6876 },
6877#endif
6878#ifdef CONFIG_CFS_BANDWIDTH
6879 {
6880 .name = "max",
6881 .flags = CFTYPE_NOT_ON_ROOT,
6882 .seq_show = cpu_max_show,
6883 .write = cpu_max_write,
6884 },
6885#endif
6886 { } /* terminate */
6887};
6888
073219e9 6889struct cgroup_subsys cpu_cgrp_subsys = {
92fb9748 6890 .css_alloc = cpu_cgroup_css_alloc,
96b77745 6891 .css_online = cpu_cgroup_css_online,
2f5177f0 6892 .css_released = cpu_cgroup_css_released,
92fb9748 6893 .css_free = cpu_cgroup_css_free,
d41bf8c9 6894 .css_extra_stat_show = cpu_extra_stat_show,
eeb61e53 6895 .fork = cpu_cgroup_fork,
bb9d97b6
TH
6896 .can_attach = cpu_cgroup_can_attach,
6897 .attach = cpu_cgroup_attach,
a1f7164c 6898 .legacy_cftypes = cpu_legacy_files,
0d593634 6899 .dfl_cftypes = cpu_files,
b38e42e9 6900 .early_init = true,
0d593634 6901 .threaded = true,
68318b8e
SV
6902};
6903
052f1dc7 6904#endif /* CONFIG_CGROUP_SCHED */
d842de87 6905
b637a328
PM
6906void dump_cpu_task(int cpu)
6907{
6908 pr_info("Task dump for CPU %d:\n", cpu);
6909 sched_show_task(cpu_curr(cpu));
6910}
ed82b8a1
AK
6911
6912/*
6913 * Nice levels are multiplicative, with a gentle 10% change for every
6914 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
6915 * nice 1, it will get ~10% less CPU time than another CPU-bound task
6916 * that remained on nice 0.
6917 *
6918 * The "10% effect" is relative and cumulative: from _any_ nice level,
6919 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
6920 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
6921 * If a task goes up by ~10% and another task goes down by ~10% then
6922 * the relative distance between them is ~25%.)
6923 */
6924const int sched_prio_to_weight[40] = {
6925 /* -20 */ 88761, 71755, 56483, 46273, 36291,
6926 /* -15 */ 29154, 23254, 18705, 14949, 11916,
6927 /* -10 */ 9548, 7620, 6100, 4904, 3906,
6928 /* -5 */ 3121, 2501, 1991, 1586, 1277,
6929 /* 0 */ 1024, 820, 655, 526, 423,
6930 /* 5 */ 335, 272, 215, 172, 137,
6931 /* 10 */ 110, 87, 70, 56, 45,
6932 /* 15 */ 36, 29, 23, 18, 15,
6933};
6934
6935/*
6936 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
6937 *
6938 * In cases where the weight does not change often, we can use the
6939 * precalculated inverse to speed up arithmetics by turning divisions
6940 * into multiplications:
6941 */
6942const u32 sched_prio_to_wmult[40] = {
6943 /* -20 */ 48388, 59856, 76040, 92818, 118348,
6944 /* -15 */ 147320, 184698, 229616, 287308, 360437,
6945 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
6946 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
6947 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
6948 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
6949 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
6950 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
6951};