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