xref: /linux/kernel/sched/syscalls.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  kernel/sched/syscalls.c
4  *
5  *  Core kernel scheduler syscalls related code
6  *
7  *  Copyright (C) 1991-2002  Linus Torvalds
8  *  Copyright (C) 1998-2024  Ingo Molnar, Red Hat
9  */
10 #include <linux/sched.h>
11 #include <linux/cpuset.h>
12 #include <linux/sched/debug.h>
13 
14 #include <uapi/linux/sched/types.h>
15 
16 #include "sched.h"
17 #include "autogroup.h"
18 
19 static inline int __normal_prio(int policy, int rt_prio, int nice)
20 {
21 	int prio;
22 
23 	if (dl_policy(policy))
24 		prio = MAX_DL_PRIO - 1;
25 	else if (rt_policy(policy))
26 		prio = MAX_RT_PRIO - 1 - rt_prio;
27 	else
28 		prio = NICE_TO_PRIO(nice);
29 
30 	return prio;
31 }
32 
33 /*
34  * Calculate the expected normal priority: i.e. priority
35  * without taking RT-inheritance into account. Might be
36  * boosted by interactivity modifiers. Changes upon fork,
37  * setprio syscalls, and whenever the interactivity
38  * estimator recalculates.
39  */
40 static inline int normal_prio(struct task_struct *p)
41 {
42 	return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio));
43 }
44 
45 /*
46  * Calculate the current priority, i.e. the priority
47  * taken into account by the scheduler. This value might
48  * be boosted by RT tasks, or might be boosted by
49  * interactivity modifiers. Will be RT if the task got
50  * RT-boosted. If not then it returns p->normal_prio.
51  */
52 static int effective_prio(struct task_struct *p)
53 {
54 	p->normal_prio = normal_prio(p);
55 	/*
56 	 * If we are RT tasks or we were boosted to RT priority,
57 	 * keep the priority unchanged. Otherwise, update priority
58 	 * to the normal priority:
59 	 */
60 	if (!rt_or_dl_prio(p->prio))
61 		return p->normal_prio;
62 	return p->prio;
63 }
64 
65 void set_user_nice(struct task_struct *p, long nice)
66 {
67 	int old_prio;
68 
69 	if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
70 		return;
71 	/*
72 	 * We have to be careful, if called from sys_setpriority(),
73 	 * the task might be in the middle of scheduling on another CPU.
74 	 */
75 	guard(task_rq_lock)(p);
76 
77 	/*
78 	 * The RT priorities are set via sched_setscheduler(), but we still
79 	 * allow the 'normal' nice value to be set - but as expected
80 	 * it won't have any effect on scheduling until the task is
81 	 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
82 	 */
83 	if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
84 		p->static_prio = NICE_TO_PRIO(nice);
85 		return;
86 	}
87 
88 	scoped_guard (sched_change, p, DEQUEUE_SAVE) {
89 		p->static_prio = NICE_TO_PRIO(nice);
90 		set_load_weight(p, true);
91 		old_prio = p->prio;
92 		p->prio = effective_prio(p);
93 	}
94 }
95 EXPORT_SYMBOL(set_user_nice);
96 
97 /*
98  * is_nice_reduction - check if nice value is an actual reduction
99  *
100  * Similar to can_nice() but does not perform a capability check.
101  *
102  * @p: task
103  * @nice: nice value
104  */
105 static bool is_nice_reduction(const struct task_struct *p, const int nice)
106 {
107 	/* Convert nice value [19,-20] to rlimit style value [1,40]: */
108 	int nice_rlim = nice_to_rlimit(nice);
109 
110 	return (nice_rlim <= task_rlimit(p, RLIMIT_NICE));
111 }
112 
113 /*
114  * can_nice - check if a task can reduce its nice value
115  * @p: task
116  * @nice: nice value
117  */
118 int can_nice(const struct task_struct *p, const int nice)
119 {
120 	return is_nice_reduction(p, nice) || capable(CAP_SYS_NICE);
121 }
122 
123 #ifdef __ARCH_WANT_SYS_NICE
124 
125 /*
126  * sys_nice - change the priority of the current process.
127  * @increment: priority increment
128  *
129  * sys_setpriority is a more generic, but much slower function that
130  * does similar things.
131  */
132 SYSCALL_DEFINE1(nice, int, increment)
133 {
134 	long nice, retval;
135 
136 	/*
137 	 * Setpriority might change our priority at the same moment.
138 	 * We don't have to worry. Conceptually one call occurs first
139 	 * and we have a single winner.
140 	 */
141 	increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
142 	nice = task_nice(current) + increment;
143 
144 	nice = clamp_val(nice, MIN_NICE, MAX_NICE);
145 	if (increment < 0 && !can_nice(current, nice))
146 		return -EPERM;
147 
148 	retval = security_task_setnice(current, nice);
149 	if (retval)
150 		return retval;
151 
152 	set_user_nice(current, nice);
153 	return 0;
154 }
155 
156 #endif /* __ARCH_WANT_SYS_NICE */
157 
158 /**
159  * task_prio - return the priority value of a given task.
160  * @p: the task in question.
161  *
162  * Return: The priority value as seen by users in /proc.
163  *
164  * sched policy         return value   kernel prio    user prio/nice
165  *
166  * normal, batch, idle     [0 ... 39]  [100 ... 139]          0/[-20 ... 19]
167  * fifo, rr             [-2 ... -100]     [98 ... 0]  [1 ... 99]
168  * deadline                     -101             -1           0
169  */
170 int task_prio(const struct task_struct *p)
171 {
172 	return p->prio - MAX_RT_PRIO;
173 }
174 
175 /**
176  * idle_cpu - is a given CPU idle currently?
177  * @cpu: the processor in question.
178  *
179  * Return: 1 if the CPU is currently idle. 0 otherwise.
180  */
181 int idle_cpu(int cpu)
182 {
183 	return idle_rq(cpu_rq(cpu));
184 }
185 
186 /**
187  * idle_task - return the idle task for a given CPU.
188  * @cpu: the processor in question.
189  *
190  * Return: The idle task for the CPU @cpu.
191  */
192 struct task_struct *idle_task(int cpu)
193 {
194 	return cpu_rq(cpu)->idle;
195 }
196 
197 #ifdef CONFIG_SCHED_CORE
198 int sched_core_idle_cpu(int cpu)
199 {
200 	struct rq *rq = cpu_rq(cpu);
201 
202 	if (sched_core_enabled(rq) && rq->curr == rq->idle)
203 		return 1;
204 
205 	return idle_cpu(cpu);
206 }
207 #endif /* CONFIG_SCHED_CORE */
208 
209 /**
210  * find_process_by_pid - find a process with a matching PID value.
211  * @pid: the pid in question.
212  *
213  * The task of @pid, if found. %NULL otherwise.
214  */
215 static struct task_struct *find_process_by_pid(pid_t pid)
216 {
217 	return pid ? find_task_by_vpid(pid) : current;
218 }
219 
220 static struct task_struct *find_get_task(pid_t pid)
221 {
222 	struct task_struct *p;
223 	guard(rcu)();
224 
225 	p = find_process_by_pid(pid);
226 	if (likely(p))
227 		get_task_struct(p);
228 
229 	return p;
230 }
231 
232 DEFINE_CLASS(find_get_task, struct task_struct *, if (_T) put_task_struct(_T),
233 	     find_get_task(pid), pid_t pid)
234 
235 /*
236  * sched_setparam() passes in -1 for its policy, to let the functions
237  * it calls know not to change it.
238  */
239 #define SETPARAM_POLICY	-1
240 
241 static void __setscheduler_params(struct task_struct *p,
242 		const struct sched_attr *attr)
243 {
244 	int policy = attr->sched_policy;
245 
246 	if (policy == SETPARAM_POLICY)
247 		policy = p->policy;
248 
249 	p->policy = policy;
250 
251 	if (dl_policy(policy))
252 		__setparam_dl(p, attr);
253 	else if (fair_policy(policy))
254 		__setparam_fair(p, attr);
255 
256 	/* rt-policy tasks do not have a timerslack */
257 	if (rt_or_dl_task_policy(p)) {
258 		p->timer_slack_ns = 0;
259 	} else if (p->timer_slack_ns == 0) {
260 		/* when switching back to non-rt policy, restore timerslack */
261 		p->timer_slack_ns = p->default_timer_slack_ns;
262 	}
263 
264 	/*
265 	 * __sched_setscheduler() ensures attr->sched_priority == 0 when
266 	 * !rt_policy. Always setting this ensures that things like
267 	 * getparam()/getattr() don't report silly values for !rt tasks.
268 	 */
269 	p->rt_priority = attr->sched_priority;
270 	p->normal_prio = normal_prio(p);
271 	set_load_weight(p, true);
272 }
273 
274 /*
275  * Check the target process has a UID that matches the current process's:
276  */
277 static bool check_same_owner(struct task_struct *p)
278 {
279 	const struct cred *cred = current_cred(), *pcred;
280 	guard(rcu)();
281 
282 	pcred = __task_cred(p);
283 	return (uid_eq(cred->euid, pcred->euid) ||
284 		uid_eq(cred->euid, pcred->uid));
285 }
286 
287 #ifdef CONFIG_RT_MUTEXES
288 static inline void __setscheduler_dl_pi(int newprio, int policy,
289 			      struct task_struct *p,
290 			      struct sched_change_ctx *scope)
291 {
292 	/*
293 	 * In case a DEADLINE task (either proper or boosted) gets
294 	 * setscheduled to a lower priority class, check if it neeeds to
295 	 * inherit parameters from a potential pi_task. In that case make
296 	 * sure replenishment happens with the next enqueue.
297 	 */
298 
299 	if (dl_prio(newprio) && !dl_policy(policy)) {
300 		struct task_struct *pi_task = rt_mutex_get_top_task(p);
301 
302 		if (pi_task) {
303 			p->dl.pi_se = pi_task->dl.pi_se;
304 			scope->flags |= ENQUEUE_REPLENISH;
305 		}
306 	}
307 }
308 #else /* !CONFIG_RT_MUTEXES */
309 static inline void __setscheduler_dl_pi(int newprio, int policy,
310 			      struct task_struct *p,
311 			      struct sched_change_ctx *scope)
312 {
313 }
314 #endif /* !CONFIG_RT_MUTEXES */
315 
316 #ifdef CONFIG_UCLAMP_TASK
317 
318 static int uclamp_validate(struct task_struct *p,
319 			   const struct sched_attr *attr)
320 {
321 	unsigned int util_min = p->uclamp_req[UCLAMP_MIN].value;
322 	unsigned int util_max = p->uclamp_req[UCLAMP_MAX].value;
323 
324 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
325 		util_min = attr->sched_util_min;
326 
327 		if (util_min + 1 > SCHED_CAPACITY_SCALE + 1)
328 			return -EINVAL;
329 	}
330 
331 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
332 		util_max = attr->sched_util_max;
333 
334 		if (util_max + 1 > SCHED_CAPACITY_SCALE + 1)
335 			return -EINVAL;
336 	}
337 
338 	if (util_min != -1 && util_max != -1 && util_min > util_max)
339 		return -EINVAL;
340 
341 	/*
342 	 * We have valid uclamp attributes; make sure uclamp is enabled.
343 	 *
344 	 * We need to do that here, because enabling static branches is a
345 	 * blocking operation which obviously cannot be done while holding
346 	 * scheduler locks.
347 	 */
348 	sched_uclamp_enable();
349 
350 	return 0;
351 }
352 
353 static bool uclamp_reset(const struct sched_attr *attr,
354 			 enum uclamp_id clamp_id,
355 			 struct uclamp_se *uc_se)
356 {
357 	/* Reset on sched class change for a non user-defined clamp value. */
358 	if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)) &&
359 	    !uc_se->user_defined)
360 		return true;
361 
362 	/* Reset on sched_util_{min,max} == -1. */
363 	if (clamp_id == UCLAMP_MIN &&
364 	    attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
365 	    attr->sched_util_min == -1) {
366 		return true;
367 	}
368 
369 	if (clamp_id == UCLAMP_MAX &&
370 	    attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
371 	    attr->sched_util_max == -1) {
372 		return true;
373 	}
374 
375 	return false;
376 }
377 
378 static void __setscheduler_uclamp(struct task_struct *p,
379 				  const struct sched_attr *attr)
380 {
381 	enum uclamp_id clamp_id;
382 
383 	for_each_clamp_id(clamp_id) {
384 		struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
385 		unsigned int value;
386 
387 		if (!uclamp_reset(attr, clamp_id, uc_se))
388 			continue;
389 
390 		/*
391 		 * RT by default have a 100% boost value that could be modified
392 		 * at runtime.
393 		 */
394 		if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
395 			value = sysctl_sched_uclamp_util_min_rt_default;
396 		else
397 			value = uclamp_none(clamp_id);
398 
399 		uclamp_se_set(uc_se, value, false);
400 
401 	}
402 
403 	if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
404 		return;
405 
406 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN &&
407 	    attr->sched_util_min != -1) {
408 		uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
409 			      attr->sched_util_min, true);
410 	}
411 
412 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX &&
413 	    attr->sched_util_max != -1) {
414 		uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
415 			      attr->sched_util_max, true);
416 	}
417 }
418 
419 #else /* !CONFIG_UCLAMP_TASK: */
420 
421 static inline int uclamp_validate(struct task_struct *p,
422 				  const struct sched_attr *attr)
423 {
424 	return -EOPNOTSUPP;
425 }
426 static void __setscheduler_uclamp(struct task_struct *p,
427 				  const struct sched_attr *attr) { }
428 #endif /* !CONFIG_UCLAMP_TASK */
429 
430 /*
431  * Allow unprivileged RT tasks to decrease priority.
432  * Only issue a capable test if needed and only once to avoid an audit
433  * event on permitted non-privileged operations:
434  */
435 static int user_check_sched_setscheduler(struct task_struct *p,
436 					 const struct sched_attr *attr,
437 					 int policy, int reset_on_fork)
438 {
439 	if (fair_policy(policy)) {
440 		if (attr->sched_nice < task_nice(p) &&
441 		    !is_nice_reduction(p, attr->sched_nice))
442 			goto req_priv;
443 	}
444 
445 	if (rt_policy(policy)) {
446 		unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO);
447 
448 		/* Can't set/change the rt policy: */
449 		if (policy != p->policy && !rlim_rtprio)
450 			goto req_priv;
451 
452 		/* Can't increase priority: */
453 		if (attr->sched_priority > p->rt_priority &&
454 		    attr->sched_priority > rlim_rtprio)
455 			goto req_priv;
456 	}
457 
458 	/*
459 	 * Can't set/change SCHED_DEADLINE policy at all for now
460 	 * (safest behavior); in the future we would like to allow
461 	 * unprivileged DL tasks to increase their relative deadline
462 	 * or reduce their runtime (both ways reducing utilization)
463 	 */
464 	if (dl_policy(policy))
465 		goto req_priv;
466 
467 	/*
468 	 * Treat SCHED_IDLE as nice 20. Only allow a switch to
469 	 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
470 	 */
471 	if (task_has_idle_policy(p) && !idle_policy(policy)) {
472 		if (!is_nice_reduction(p, task_nice(p)))
473 			goto req_priv;
474 	}
475 
476 	/* Can't change other user's priorities: */
477 	if (!check_same_owner(p))
478 		goto req_priv;
479 
480 	/* Normal users shall not reset the sched_reset_on_fork flag: */
481 	if (p->sched_reset_on_fork && !reset_on_fork)
482 		goto req_priv;
483 
484 	return 0;
485 
486 req_priv:
487 	if (!capable(CAP_SYS_NICE))
488 		return -EPERM;
489 
490 	return 0;
491 }
492 
493 int __sched_setscheduler(struct task_struct *p,
494 			 const struct sched_attr *attr,
495 			 bool user, bool pi)
496 {
497 	int oldpolicy = -1, policy = attr->sched_policy;
498 	int retval, oldprio, newprio;
499 	const struct sched_class *prev_class, *next_class;
500 	struct balance_callback *head;
501 	struct rq_flags rf;
502 	int reset_on_fork;
503 	int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
504 	struct rq *rq;
505 	bool cpuset_locked = false;
506 
507 	/* The pi code expects interrupts enabled */
508 	BUG_ON(pi && in_interrupt());
509 recheck:
510 	/* Double check policy once rq lock held: */
511 	if (policy < 0) {
512 		reset_on_fork = p->sched_reset_on_fork;
513 		policy = oldpolicy = p->policy;
514 	} else {
515 		reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
516 
517 		if (!valid_policy(policy))
518 			return -EINVAL;
519 	}
520 
521 	if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
522 		return -EINVAL;
523 
524 	/*
525 	 * Valid priorities for SCHED_FIFO and SCHED_RR are
526 	 * 1..MAX_RT_PRIO-1, valid priority for SCHED_NORMAL,
527 	 * SCHED_BATCH and SCHED_IDLE is 0.
528 	 */
529 	if (attr->sched_priority > MAX_RT_PRIO-1)
530 		return -EINVAL;
531 	if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
532 	    (rt_policy(policy) != (attr->sched_priority != 0)))
533 		return -EINVAL;
534 
535 	if (user) {
536 		retval = user_check_sched_setscheduler(p, attr, policy, reset_on_fork);
537 		if (retval)
538 			return retval;
539 
540 		if (attr->sched_flags & SCHED_FLAG_SUGOV)
541 			return -EINVAL;
542 
543 		retval = security_task_setscheduler(p);
544 		if (retval)
545 			return retval;
546 	}
547 
548 	/* Update task specific "requested" clamps */
549 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
550 		retval = uclamp_validate(p, attr);
551 		if (retval)
552 			return retval;
553 	}
554 
555 	/*
556 	 * SCHED_DEADLINE bandwidth accounting relies on stable cpusets
557 	 * information.
558 	 */
559 	if (dl_policy(policy) || dl_policy(p->policy)) {
560 		cpuset_locked = true;
561 		cpuset_lock();
562 	}
563 
564 	/*
565 	 * Make sure no PI-waiters arrive (or leave) while we are
566 	 * changing the priority of the task:
567 	 *
568 	 * To be able to change p->policy safely, the appropriate
569 	 * runqueue lock must be held.
570 	 */
571 	rq = task_rq_lock(p, &rf);
572 	update_rq_clock(rq);
573 
574 	/*
575 	 * Changing the policy of the stop threads its a very bad idea:
576 	 */
577 	if (p == rq->stop) {
578 		retval = -EINVAL;
579 		goto unlock;
580 	}
581 
582 	retval = scx_check_setscheduler(p, policy);
583 	if (retval)
584 		goto unlock;
585 
586 	/*
587 	 * If not changing anything there's no need to proceed further,
588 	 * but store a possible modification of reset_on_fork.
589 	 */
590 	if (unlikely(policy == p->policy)) {
591 		if (fair_policy(policy) &&
592 		    (attr->sched_nice != task_nice(p) ||
593 		     (attr->sched_runtime != p->se.slice)))
594 			goto change;
595 		if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
596 			goto change;
597 		if (dl_policy(policy) && dl_param_changed(p, attr))
598 			goto change;
599 		if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
600 			goto change;
601 
602 		p->sched_reset_on_fork = reset_on_fork;
603 		retval = 0;
604 		goto unlock;
605 	}
606 change:
607 
608 	if (user) {
609 #ifdef CONFIG_RT_GROUP_SCHED
610 		/*
611 		 * Do not allow real-time tasks into groups that have no runtime
612 		 * assigned.
613 		 */
614 		if (rt_group_sched_enabled() &&
615 				rt_bandwidth_enabled() && rt_policy(policy) &&
616 				task_group(p)->rt_bandwidth.rt_runtime == 0 &&
617 				!task_group_is_autogroup(task_group(p))) {
618 			retval = -EPERM;
619 			goto unlock;
620 		}
621 #endif /* CONFIG_RT_GROUP_SCHED */
622 		if (dl_bandwidth_enabled() && dl_policy(policy) &&
623 				!(attr->sched_flags & SCHED_FLAG_SUGOV)) {
624 			cpumask_t *span = rq->rd->span;
625 
626 			/*
627 			 * Don't allow tasks with an affinity mask smaller than
628 			 * the entire root_domain to become SCHED_DEADLINE. We
629 			 * will also fail if there's no bandwidth available.
630 			 */
631 			if (!cpumask_subset(span, &p->cpus_mask) ||
632 			    rq->rd->dl_bw.bw == 0) {
633 				retval = -EPERM;
634 				goto unlock;
635 			}
636 		}
637 	}
638 
639 	/* Re-check policy now with rq lock held: */
640 	if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
641 		policy = oldpolicy = -1;
642 		task_rq_unlock(rq, p, &rf);
643 		if (cpuset_locked) {
644 			cpuset_unlock();
645 			cpuset_locked = false;
646 		}
647 		goto recheck;
648 	}
649 
650 	/*
651 	 * If setscheduling to SCHED_DEADLINE (or changing the parameters
652 	 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
653 	 * is available.
654 	 */
655 	if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
656 		retval = -EBUSY;
657 		goto unlock;
658 	}
659 
660 	p->sched_reset_on_fork = reset_on_fork;
661 	oldprio = p->prio;
662 
663 	newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
664 	if (pi) {
665 		/*
666 		 * Take priority boosted tasks into account. If the new
667 		 * effective priority is unchanged, we just store the new
668 		 * normal parameters and do not touch the scheduler class and
669 		 * the runqueue. This will be done when the task deboost
670 		 * itself.
671 		 */
672 		newprio = rt_effective_prio(p, newprio);
673 		if (newprio == oldprio && !dl_prio(newprio))
674 			queue_flags &= ~DEQUEUE_MOVE;
675 	}
676 
677 	prev_class = p->sched_class;
678 	next_class = __setscheduler_class(policy, newprio);
679 
680 	if (prev_class != next_class)
681 		queue_flags |= DEQUEUE_CLASS;
682 
683 	scx_prepare_setscheduler(p, policy);
684 
685 	scoped_guard (sched_change, p, queue_flags) {
686 
687 		if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
688 			__setscheduler_params(p, attr);
689 			p->sched_class = next_class;
690 			p->prio = newprio;
691 			__setscheduler_dl_pi(newprio, policy, p, scope);
692 		}
693 		__setscheduler_uclamp(p, attr);
694 
695 		if (scope->queued) {
696 			/*
697 			 * We enqueue to tail when the priority of a task is
698 			 * increased (user space view).
699 			 */
700 			if (oldprio < p->prio)
701 				scope->flags |= ENQUEUE_HEAD;
702 		}
703 	}
704 
705 	/* Avoid rq from going away on us: */
706 	preempt_disable();
707 	head = splice_balance_callbacks(rq);
708 	task_rq_unlock(rq, p, &rf);
709 
710 	if (pi) {
711 		if (cpuset_locked)
712 			cpuset_unlock();
713 		rt_mutex_adjust_pi(p);
714 	}
715 
716 	/* Run balance callbacks after we've adjusted the PI chain: */
717 	balance_callbacks(rq, head);
718 	preempt_enable();
719 
720 	return 0;
721 
722 unlock:
723 	task_rq_unlock(rq, p, &rf);
724 	if (cpuset_locked)
725 		cpuset_unlock();
726 	return retval;
727 }
728 
729 static int _sched_setscheduler(struct task_struct *p, int policy,
730 			       const struct sched_param *param, bool check)
731 {
732 	struct sched_attr attr = {
733 		.sched_policy   = policy,
734 		.sched_priority = param->sched_priority,
735 		.sched_nice	= PRIO_TO_NICE(p->static_prio),
736 	};
737 
738 	if (p->se.custom_slice)
739 		attr.sched_runtime = p->se.slice;
740 
741 	/* Fixup the legacy SCHED_RESET_ON_FORK hack. */
742 	if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
743 		attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
744 		policy &= ~SCHED_RESET_ON_FORK;
745 		attr.sched_policy = policy;
746 	}
747 
748 	return __sched_setscheduler(p, &attr, check, true);
749 }
750 /**
751  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
752  * @p: the task in question.
753  * @policy: new policy.
754  * @param: structure containing the new RT priority.
755  *
756  * Use sched_set_fifo(), read its comment.
757  *
758  * Return: 0 on success. An error code otherwise.
759  *
760  * NOTE that the task may be already dead.
761  */
762 int sched_setscheduler(struct task_struct *p, int policy,
763 		       const struct sched_param *param)
764 {
765 	return _sched_setscheduler(p, policy, param, true);
766 }
767 
768 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
769 {
770 	return __sched_setscheduler(p, attr, true, true);
771 }
772 
773 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
774 {
775 	return __sched_setscheduler(p, attr, false, true);
776 }
777 EXPORT_SYMBOL_GPL(sched_setattr_nocheck);
778 
779 /**
780  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernel-space.
781  * @p: the task in question.
782  * @policy: new policy.
783  * @param: structure containing the new RT priority.
784  *
785  * Just like sched_setscheduler, only don't bother checking if the
786  * current context has permission.  For example, this is needed in
787  * stop_machine(): we create temporary high priority worker threads,
788  * but our caller might not have that capability.
789  *
790  * Return: 0 on success. An error code otherwise.
791  */
792 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
793 			       const struct sched_param *param)
794 {
795 	return _sched_setscheduler(p, policy, param, false);
796 }
797 
798 /*
799  * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
800  * incapable of resource management, which is the one thing an OS really should
801  * be doing.
802  *
803  * This is of course the reason it is limited to privileged users only.
804  *
805  * Worse still; it is fundamentally impossible to compose static priority
806  * workloads. You cannot take two correctly working static prio workloads
807  * and smash them together and still expect them to work.
808  *
809  * For this reason 'all' FIFO tasks the kernel creates are basically at:
810  *
811  *   MAX_RT_PRIO / 2
812  *
813  * The administrator _MUST_ configure the system, the kernel simply doesn't
814  * know enough information to make a sensible choice.
815  */
816 void sched_set_fifo(struct task_struct *p)
817 {
818 	struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
819 	WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
820 }
821 EXPORT_SYMBOL_GPL(sched_set_fifo);
822 
823 /*
824  * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
825  */
826 void sched_set_fifo_low(struct task_struct *p)
827 {
828 	struct sched_param sp = { .sched_priority = 1 };
829 	WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
830 }
831 EXPORT_SYMBOL_GPL(sched_set_fifo_low);
832 
833 /*
834  * Used when the primary interrupt handler is forced into a thread, in addition
835  * to the (always threaded) secondary handler.  The secondary handler gets a
836  * slightly lower priority so that the primary handler can preempt it, thereby
837  * emulating the behavior of a non-PREEMPT_RT system where the primary handler
838  * runs in hard interrupt context.
839  */
840 void sched_set_fifo_secondary(struct task_struct *p)
841 {
842 	struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 - 1 };
843 	WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
844 }
845 
846 void sched_set_normal(struct task_struct *p, int nice)
847 {
848 	struct sched_attr attr = {
849 		.sched_policy = SCHED_NORMAL,
850 		.sched_nice = nice,
851 	};
852 	WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
853 }
854 EXPORT_SYMBOL_GPL(sched_set_normal);
855 
856 static int
857 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
858 {
859 	struct sched_param lparam;
860 
861 	if (unlikely(!param || pid < 0))
862 		return -EINVAL;
863 	if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
864 		return -EFAULT;
865 
866 	CLASS(find_get_task, p)(pid);
867 	if (!p)
868 		return -ESRCH;
869 
870 	return sched_setscheduler(p, policy, &lparam);
871 }
872 
873 /*
874  * Mimics kernel/events/core.c perf_copy_attr().
875  */
876 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
877 {
878 	u32 size;
879 	int ret;
880 
881 	/* Zero the full structure, so that a short copy will be nice: */
882 	memset(attr, 0, sizeof(*attr));
883 
884 	ret = get_user(size, &uattr->size);
885 	if (ret)
886 		return ret;
887 
888 	/* ABI compatibility quirk: */
889 	if (!size)
890 		size = SCHED_ATTR_SIZE_VER0;
891 	if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
892 		goto err_size;
893 
894 	ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
895 	if (ret) {
896 		if (ret == -E2BIG)
897 			goto err_size;
898 		return ret;
899 	}
900 
901 	if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
902 	    size < SCHED_ATTR_SIZE_VER1)
903 		return -EINVAL;
904 
905 	/*
906 	 * XXX: Do we want to be lenient like existing syscalls; or do we want
907 	 * to be strict and return an error on out-of-bounds values?
908 	 */
909 	attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
910 
911 	return 0;
912 
913 err_size:
914 	put_user(sizeof(*attr), &uattr->size);
915 	return -E2BIG;
916 }
917 
918 static void get_params(struct task_struct *p, struct sched_attr *attr, unsigned int flags)
919 {
920 	if (task_has_dl_policy(p)) {
921 		__getparam_dl(p, attr, flags);
922 	} else if (task_has_rt_policy(p)) {
923 		attr->sched_priority = p->rt_priority;
924 	} else {
925 		attr->sched_nice = task_nice(p);
926 		attr->sched_runtime = p->se.slice;
927 	}
928 }
929 
930 /**
931  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
932  * @pid: the pid in question.
933  * @policy: new policy.
934  * @param: structure containing the new RT priority.
935  *
936  * Return: 0 on success. An error code otherwise.
937  */
938 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
939 {
940 	if (policy < 0)
941 		return -EINVAL;
942 
943 	return do_sched_setscheduler(pid, policy, param);
944 }
945 
946 /**
947  * sys_sched_setparam - set/change the RT priority of a thread
948  * @pid: the pid in question.
949  * @param: structure containing the new RT priority.
950  *
951  * Return: 0 on success. An error code otherwise.
952  */
953 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
954 {
955 	return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
956 }
957 
958 /**
959  * sys_sched_setattr - same as above, but with extended sched_attr
960  * @pid: the pid in question.
961  * @uattr: structure containing the extended parameters.
962  * @flags: for future extension.
963  */
964 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
965 			       unsigned int, flags)
966 {
967 	struct sched_attr attr;
968 	int retval;
969 
970 	if (unlikely(!uattr || pid < 0 || flags))
971 		return -EINVAL;
972 
973 	retval = sched_copy_attr(uattr, &attr);
974 	if (retval)
975 		return retval;
976 
977 	if ((int)attr.sched_policy < 0)
978 		return -EINVAL;
979 	if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
980 		attr.sched_policy = SETPARAM_POLICY;
981 
982 	CLASS(find_get_task, p)(pid);
983 	if (!p)
984 		return -ESRCH;
985 
986 	if (attr.sched_flags & SCHED_FLAG_KEEP_PARAMS)
987 		get_params(p, &attr, 0);
988 
989 	return sched_setattr(p, &attr);
990 }
991 
992 /**
993  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
994  * @pid: the pid in question.
995  *
996  * Return: On success, the policy of the thread. Otherwise, a negative error
997  * code.
998  */
999 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
1000 {
1001 	struct task_struct *p;
1002 	int retval;
1003 
1004 	if (pid < 0)
1005 		return -EINVAL;
1006 
1007 	guard(rcu)();
1008 	p = find_process_by_pid(pid);
1009 	if (!p)
1010 		return -ESRCH;
1011 
1012 	retval = security_task_getscheduler(p);
1013 	if (!retval) {
1014 		retval = p->policy;
1015 		if (p->sched_reset_on_fork)
1016 			retval |= SCHED_RESET_ON_FORK;
1017 	}
1018 	return retval;
1019 }
1020 
1021 /**
1022  * sys_sched_getparam - get the RT priority of a thread
1023  * @pid: the pid in question.
1024  * @param: structure containing the RT priority.
1025  *
1026  * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
1027  * code.
1028  */
1029 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
1030 {
1031 	struct sched_param lp = { .sched_priority = 0 };
1032 	struct task_struct *p;
1033 	int retval;
1034 
1035 	if (unlikely(!param || pid < 0))
1036 		return -EINVAL;
1037 
1038 	scoped_guard (rcu) {
1039 		p = find_process_by_pid(pid);
1040 		if (!p)
1041 			return -ESRCH;
1042 
1043 		retval = security_task_getscheduler(p);
1044 		if (retval)
1045 			return retval;
1046 
1047 		if (task_has_rt_policy(p))
1048 			lp.sched_priority = p->rt_priority;
1049 	}
1050 
1051 	/*
1052 	 * This one might sleep, we cannot do it with a spinlock held ...
1053 	 */
1054 	return copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
1055 }
1056 
1057 /**
1058  * sys_sched_getattr - similar to sched_getparam, but with sched_attr
1059  * @pid: the pid in question.
1060  * @uattr: structure containing the extended parameters.
1061  * @usize: sizeof(attr) for fwd/bwd comp.
1062  * @flags: for future extension.
1063  */
1064 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
1065 		unsigned int, usize, unsigned int, flags)
1066 {
1067 	struct sched_attr kattr = { };
1068 	struct task_struct *p;
1069 	int retval;
1070 
1071 	if (unlikely(!uattr || pid < 0 || usize > PAGE_SIZE ||
1072 		     usize < SCHED_ATTR_SIZE_VER0))
1073 		return -EINVAL;
1074 
1075 	scoped_guard (rcu) {
1076 		p = find_process_by_pid(pid);
1077 		if (!p)
1078 			return -ESRCH;
1079 
1080 		if (flags) {
1081 			if (!task_has_dl_policy(p) ||
1082 			    flags != SCHED_GETATTR_FLAG_DL_DYNAMIC)
1083 				return -EINVAL;
1084 		}
1085 
1086 		retval = security_task_getscheduler(p);
1087 		if (retval)
1088 			return retval;
1089 
1090 		kattr.sched_policy = p->policy;
1091 		if (p->sched_reset_on_fork)
1092 			kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
1093 		get_params(p, &kattr, flags);
1094 		kattr.sched_flags &= SCHED_FLAG_ALL;
1095 
1096 #ifdef CONFIG_UCLAMP_TASK
1097 		/*
1098 		 * This could race with another potential updater, but this is fine
1099 		 * because it'll correctly read the old or the new value. We don't need
1100 		 * to guarantee who wins the race as long as it doesn't return garbage.
1101 		 */
1102 		kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
1103 		kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
1104 #endif
1105 	}
1106 
1107 	kattr.size = min(usize, sizeof(kattr));
1108 	return copy_struct_to_user(uattr, usize, &kattr, sizeof(kattr), NULL);
1109 }
1110 
1111 int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
1112 {
1113 	/*
1114 	 * If the task isn't a deadline task or admission control is
1115 	 * disabled then we don't care about affinity changes.
1116 	 */
1117 	if (!task_has_dl_policy(p) || !dl_bandwidth_enabled())
1118 		return 0;
1119 
1120 	/*
1121 	 * The special/sugov task isn't part of regular bandwidth/admission
1122 	 * control so let userspace change affinities.
1123 	 */
1124 	if (dl_entity_is_special(&p->dl))
1125 		return 0;
1126 
1127 	/*
1128 	 * Since bandwidth control happens on root_domain basis,
1129 	 * if admission test is enabled, we only admit -deadline
1130 	 * tasks allowed to run on all the CPUs in the task's
1131 	 * root_domain.
1132 	 */
1133 	guard(rcu)();
1134 	if (!cpumask_subset(task_rq(p)->rd->span, mask))
1135 		return -EBUSY;
1136 
1137 	return 0;
1138 }
1139 
1140 int __sched_setaffinity(struct task_struct *p, struct affinity_context *ctx)
1141 {
1142 	int retval;
1143 	cpumask_var_t cpus_allowed, new_mask;
1144 
1145 	if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL))
1146 		return -ENOMEM;
1147 
1148 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
1149 		retval = -ENOMEM;
1150 		goto out_free_cpus_allowed;
1151 	}
1152 
1153 	cpuset_cpus_allowed(p, cpus_allowed);
1154 	cpumask_and(new_mask, ctx->new_mask, cpus_allowed);
1155 
1156 	ctx->new_mask = new_mask;
1157 	ctx->flags |= SCA_CHECK;
1158 
1159 	retval = dl_task_check_affinity(p, new_mask);
1160 	if (retval)
1161 		goto out_free_new_mask;
1162 
1163 	retval = __set_cpus_allowed_ptr(p, ctx);
1164 	if (retval)
1165 		goto out_free_new_mask;
1166 
1167 	cpuset_cpus_allowed(p, cpus_allowed);
1168 	if (!cpumask_subset(new_mask, cpus_allowed)) {
1169 		/*
1170 		 * We must have raced with a concurrent cpuset update.
1171 		 * Just reset the cpumask to the cpuset's cpus_allowed.
1172 		 */
1173 		cpumask_copy(new_mask, cpus_allowed);
1174 
1175 		/*
1176 		 * If SCA_USER is set, a 2nd call to __set_cpus_allowed_ptr()
1177 		 * will restore the previous user_cpus_ptr value.
1178 		 *
1179 		 * In the unlikely event a previous user_cpus_ptr exists,
1180 		 * we need to further restrict the mask to what is allowed
1181 		 * by that old user_cpus_ptr.
1182 		 */
1183 		if (unlikely((ctx->flags & SCA_USER) && ctx->user_mask)) {
1184 			bool empty = !cpumask_and(new_mask, new_mask,
1185 						  ctx->user_mask);
1186 
1187 			if (empty)
1188 				cpumask_copy(new_mask, cpus_allowed);
1189 		}
1190 		__set_cpus_allowed_ptr(p, ctx);
1191 		retval = -EINVAL;
1192 	}
1193 
1194 out_free_new_mask:
1195 	free_cpumask_var(new_mask);
1196 out_free_cpus_allowed:
1197 	free_cpumask_var(cpus_allowed);
1198 	return retval;
1199 }
1200 
1201 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
1202 {
1203 	struct affinity_context ac;
1204 	struct cpumask *user_mask;
1205 	int retval;
1206 
1207 	CLASS(find_get_task, p)(pid);
1208 	if (!p)
1209 		return -ESRCH;
1210 
1211 	if (p->flags & PF_NO_SETAFFINITY)
1212 		return -EINVAL;
1213 
1214 	if (!check_same_owner(p)) {
1215 		guard(rcu)();
1216 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE))
1217 			return -EPERM;
1218 	}
1219 
1220 	retval = security_task_setscheduler(p);
1221 	if (retval)
1222 		return retval;
1223 
1224 	/*
1225 	 * With non-SMP configs, user_cpus_ptr/user_mask isn't used and
1226 	 * alloc_user_cpus_ptr() returns NULL.
1227 	 */
1228 	user_mask = alloc_user_cpus_ptr(NUMA_NO_NODE);
1229 	if (user_mask) {
1230 		cpumask_copy(user_mask, in_mask);
1231 	} else {
1232 		return -ENOMEM;
1233 	}
1234 
1235 	ac = (struct affinity_context){
1236 		.new_mask  = in_mask,
1237 		.user_mask = user_mask,
1238 		.flags     = SCA_USER,
1239 	};
1240 
1241 	retval = __sched_setaffinity(p, &ac);
1242 	kfree(ac.user_mask);
1243 
1244 	return retval;
1245 }
1246 
1247 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
1248 			     struct cpumask *new_mask)
1249 {
1250 	if (len < cpumask_size())
1251 		cpumask_clear(new_mask);
1252 	else if (len > cpumask_size())
1253 		len = cpumask_size();
1254 
1255 	return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
1256 }
1257 
1258 /**
1259  * sys_sched_setaffinity - set the CPU affinity of a process
1260  * @pid: pid of the process
1261  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
1262  * @user_mask_ptr: user-space pointer to the new CPU mask
1263  *
1264  * Return: 0 on success. An error code otherwise.
1265  */
1266 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
1267 		unsigned long __user *, user_mask_ptr)
1268 {
1269 	cpumask_var_t new_mask;
1270 	int retval;
1271 
1272 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
1273 		return -ENOMEM;
1274 
1275 	retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
1276 	if (retval == 0)
1277 		retval = sched_setaffinity(pid, new_mask);
1278 	free_cpumask_var(new_mask);
1279 	return retval;
1280 }
1281 
1282 long sched_getaffinity(pid_t pid, struct cpumask *mask)
1283 {
1284 	struct task_struct *p;
1285 	int retval;
1286 
1287 	guard(rcu)();
1288 	p = find_process_by_pid(pid);
1289 	if (!p)
1290 		return -ESRCH;
1291 
1292 	retval = security_task_getscheduler(p);
1293 	if (retval)
1294 		return retval;
1295 
1296 	guard(raw_spinlock_irqsave)(&p->pi_lock);
1297 	cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
1298 
1299 	return 0;
1300 }
1301 
1302 /**
1303  * sys_sched_getaffinity - get the CPU affinity of a process
1304  * @pid: pid of the process
1305  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
1306  * @user_mask_ptr: user-space pointer to hold the current CPU mask
1307  *
1308  * Return: size of CPU mask copied to user_mask_ptr on success. An
1309  * error code otherwise.
1310  */
1311 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
1312 		unsigned long __user *, user_mask_ptr)
1313 {
1314 	int ret;
1315 	cpumask_var_t mask;
1316 
1317 	if ((len * BITS_PER_BYTE) < nr_cpu_ids)
1318 		return -EINVAL;
1319 	if (len & (sizeof(unsigned long)-1))
1320 		return -EINVAL;
1321 
1322 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL))
1323 		return -ENOMEM;
1324 
1325 	ret = sched_getaffinity(pid, mask);
1326 	if (ret == 0) {
1327 		unsigned int retlen = min(len, cpumask_size());
1328 
1329 		if (copy_to_user(user_mask_ptr, cpumask_bits(mask), retlen))
1330 			ret = -EFAULT;
1331 		else
1332 			ret = retlen;
1333 	}
1334 	free_cpumask_var(mask);
1335 
1336 	return ret;
1337 }
1338 
1339 static void do_sched_yield(void)
1340 {
1341 	struct rq_flags rf;
1342 	struct rq *rq;
1343 
1344 	rq = this_rq_lock_irq(&rf);
1345 
1346 	schedstat_inc(rq->yld_count);
1347 	rq->donor->sched_class->yield_task(rq);
1348 
1349 	preempt_disable();
1350 	rq_unlock_irq(rq, &rf);
1351 	sched_preempt_enable_no_resched();
1352 
1353 	schedule();
1354 }
1355 
1356 /**
1357  * sys_sched_yield - yield the current processor to other threads.
1358  *
1359  * This function yields the current CPU to other tasks. If there are no
1360  * other threads running on this CPU then this function will return.
1361  *
1362  * Return: 0.
1363  */
1364 SYSCALL_DEFINE0(sched_yield)
1365 {
1366 	do_sched_yield();
1367 	return 0;
1368 }
1369 
1370 /**
1371  * yield - yield the current processor to other threads.
1372  *
1373  * Do not ever use this function, there's a 99% chance you're doing it wrong.
1374  *
1375  * The scheduler is at all times free to pick the calling task as the most
1376  * eligible task to run, if removing the yield() call from your code breaks
1377  * it, it's already broken.
1378  *
1379  * Typical broken usage is:
1380  *
1381  * while (!event)
1382  *	yield();
1383  *
1384  * where one assumes that yield() will let 'the other' process run that will
1385  * make event true. If the current task is a SCHED_FIFO task that will never
1386  * happen. Never use yield() as a progress guarantee!!
1387  *
1388  * If you want to use yield() to wait for something, use wait_event().
1389  * If you want to use yield() to be 'nice' for others, use cond_resched().
1390  * If you still want to use yield(), do not!
1391  */
1392 void __sched yield(void)
1393 {
1394 	set_current_state(TASK_RUNNING);
1395 	do_sched_yield();
1396 }
1397 EXPORT_SYMBOL(yield);
1398 
1399 /**
1400  * yield_to - yield the current processor to another thread in
1401  * your thread group, or accelerate that thread toward the
1402  * processor it's on.
1403  * @p: target task
1404  * @preempt: whether task preemption is allowed or not
1405  *
1406  * It's the caller's job to ensure that the target task struct
1407  * can't go away on us before we can do any checks.
1408  *
1409  * Return:
1410  *	true (>0) if we indeed boosted the target task.
1411  *	false (0) if we failed to boost the target.
1412  *	-ESRCH if there's no task to yield to.
1413  */
1414 int __sched yield_to(struct task_struct *p, bool preempt)
1415 {
1416 	struct task_struct *curr;
1417 	struct rq *rq, *p_rq;
1418 	int yielded = 0;
1419 
1420 	scoped_guard (raw_spinlock_irqsave, &p->pi_lock) {
1421 		rq = this_rq();
1422 		curr = rq->donor;
1423 
1424 again:
1425 		p_rq = task_rq(p);
1426 		/*
1427 		 * If we're the only runnable task on the rq and target rq also
1428 		 * has only one task, there's absolutely no point in yielding.
1429 		 */
1430 		if (rq->nr_running == 1 && p_rq->nr_running == 1)
1431 			return -ESRCH;
1432 
1433 		guard(double_rq_lock)(rq, p_rq);
1434 		if (task_rq(p) != p_rq)
1435 			goto again;
1436 
1437 		if (!curr->sched_class->yield_to_task)
1438 			return 0;
1439 
1440 		if (curr->sched_class != p->sched_class)
1441 			return 0;
1442 
1443 		if (task_on_cpu(p_rq, p) || !task_is_running(p))
1444 			return 0;
1445 
1446 		yielded = curr->sched_class->yield_to_task(rq, p);
1447 		if (yielded) {
1448 			schedstat_inc(rq->yld_count);
1449 			/*
1450 			 * Make p's CPU reschedule; pick_next_entity
1451 			 * takes care of fairness.
1452 			 */
1453 			if (preempt && rq != p_rq)
1454 				resched_curr(p_rq);
1455 		}
1456 	}
1457 
1458 	if (yielded)
1459 		schedule();
1460 
1461 	return yielded;
1462 }
1463 EXPORT_SYMBOL_GPL(yield_to);
1464 
1465 /**
1466  * sys_sched_get_priority_max - return maximum RT priority.
1467  * @policy: scheduling class.
1468  *
1469  * Return: On success, this syscall returns the maximum
1470  * rt_priority that can be used by a given scheduling class.
1471  * On failure, a negative error code is returned.
1472  */
1473 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
1474 {
1475 	int ret = -EINVAL;
1476 
1477 	switch (policy) {
1478 	case SCHED_FIFO:
1479 	case SCHED_RR:
1480 		ret = MAX_RT_PRIO-1;
1481 		break;
1482 	case SCHED_DEADLINE:
1483 	case SCHED_NORMAL:
1484 	case SCHED_BATCH:
1485 	case SCHED_IDLE:
1486 	case SCHED_EXT:
1487 		ret = 0;
1488 		break;
1489 	}
1490 	return ret;
1491 }
1492 
1493 /**
1494  * sys_sched_get_priority_min - return minimum RT priority.
1495  * @policy: scheduling class.
1496  *
1497  * Return: On success, this syscall returns the minimum
1498  * rt_priority that can be used by a given scheduling class.
1499  * On failure, a negative error code is returned.
1500  */
1501 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
1502 {
1503 	int ret = -EINVAL;
1504 
1505 	switch (policy) {
1506 	case SCHED_FIFO:
1507 	case SCHED_RR:
1508 		ret = 1;
1509 		break;
1510 	case SCHED_DEADLINE:
1511 	case SCHED_NORMAL:
1512 	case SCHED_BATCH:
1513 	case SCHED_IDLE:
1514 	case SCHED_EXT:
1515 		ret = 0;
1516 	}
1517 	return ret;
1518 }
1519 
1520 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
1521 {
1522 	unsigned int time_slice = 0;
1523 	int retval;
1524 
1525 	if (pid < 0)
1526 		return -EINVAL;
1527 
1528 	scoped_guard (rcu) {
1529 		struct task_struct *p = find_process_by_pid(pid);
1530 		if (!p)
1531 			return -ESRCH;
1532 
1533 		retval = security_task_getscheduler(p);
1534 		if (retval)
1535 			return retval;
1536 
1537 		scoped_guard (task_rq_lock, p) {
1538 			struct rq *rq = scope.rq;
1539 			if (p->sched_class->get_rr_interval)
1540 				time_slice = p->sched_class->get_rr_interval(rq, p);
1541 		}
1542 	}
1543 
1544 	jiffies_to_timespec64(time_slice, t);
1545 	return 0;
1546 }
1547 
1548 /**
1549  * sys_sched_rr_get_interval - return the default time-slice of a process.
1550  * @pid: pid of the process.
1551  * @interval: userspace pointer to the time-slice value.
1552  *
1553  * this syscall writes the default time-slice value of a given process
1554  * into the user-space timespec buffer. A value of '0' means infinity.
1555  *
1556  * Return: On success, 0 and the time-slice is in @interval. Otherwise,
1557  * an error code.
1558  */
1559 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
1560 		struct __kernel_timespec __user *, interval)
1561 {
1562 	struct timespec64 t;
1563 	int retval = sched_rr_get_interval(pid, &t);
1564 
1565 	if (retval == 0)
1566 		retval = put_timespec64(&t, interval);
1567 
1568 	return retval;
1569 }
1570 
1571 #ifdef CONFIG_COMPAT_32BIT_TIME
1572 SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
1573 		struct old_timespec32 __user *, interval)
1574 {
1575 	struct timespec64 t;
1576 	int retval = sched_rr_get_interval(pid, &t);
1577 
1578 	if (retval == 0)
1579 		retval = put_old_timespec32(&t, interval);
1580 	return retval;
1581 }
1582 #endif
1583