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