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