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