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