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