nohz: Re-evaluate the tick from the scheduler IPI
[deliverable/linux.git] / kernel / sched / core.c
1 /*
2 * kernel/sched/core.c
3 *
4 * Kernel scheduler and related syscalls
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
7 *
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
27 */
28
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <asm/mmu_context.h>
36 #include <linux/interrupt.h>
37 #include <linux/capability.h>
38 #include <linux/completion.h>
39 #include <linux/kernel_stat.h>
40 #include <linux/debug_locks.h>
41 #include <linux/perf_event.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/proc_fs.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/unistd.h>
66 #include <linux/pagemap.h>
67 #include <linux/hrtimer.h>
68 #include <linux/tick.h>
69 #include <linux/debugfs.h>
70 #include <linux/ctype.h>
71 #include <linux/ftrace.h>
72 #include <linux/slab.h>
73 #include <linux/init_task.h>
74 #include <linux/binfmts.h>
75 #include <linux/context_tracking.h>
76
77 #include <asm/switch_to.h>
78 #include <asm/tlb.h>
79 #include <asm/irq_regs.h>
80 #include <asm/mutex.h>
81 #ifdef CONFIG_PARAVIRT
82 #include <asm/paravirt.h>
83 #endif
84
85 #include "sched.h"
86 #include "../workqueue_internal.h"
87 #include "../smpboot.h"
88
89 #define CREATE_TRACE_POINTS
90 #include <trace/events/sched.h>
91
92 void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
93 {
94 unsigned long delta;
95 ktime_t soft, hard, now;
96
97 for (;;) {
98 if (hrtimer_active(period_timer))
99 break;
100
101 now = hrtimer_cb_get_time(period_timer);
102 hrtimer_forward(period_timer, now, period);
103
104 soft = hrtimer_get_softexpires(period_timer);
105 hard = hrtimer_get_expires(period_timer);
106 delta = ktime_to_ns(ktime_sub(hard, soft));
107 __hrtimer_start_range_ns(period_timer, soft, delta,
108 HRTIMER_MODE_ABS_PINNED, 0);
109 }
110 }
111
112 DEFINE_MUTEX(sched_domains_mutex);
113 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
114
115 static void update_rq_clock_task(struct rq *rq, s64 delta);
116
117 void update_rq_clock(struct rq *rq)
118 {
119 s64 delta;
120
121 if (rq->skip_clock_update > 0)
122 return;
123
124 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
125 rq->clock += delta;
126 update_rq_clock_task(rq, delta);
127 }
128
129 /*
130 * Debugging: various feature bits
131 */
132
133 #define SCHED_FEAT(name, enabled) \
134 (1UL << __SCHED_FEAT_##name) * enabled |
135
136 const_debug unsigned int sysctl_sched_features =
137 #include "features.h"
138 0;
139
140 #undef SCHED_FEAT
141
142 #ifdef CONFIG_SCHED_DEBUG
143 #define SCHED_FEAT(name, enabled) \
144 #name ,
145
146 static const char * const sched_feat_names[] = {
147 #include "features.h"
148 };
149
150 #undef SCHED_FEAT
151
152 static int sched_feat_show(struct seq_file *m, void *v)
153 {
154 int i;
155
156 for (i = 0; i < __SCHED_FEAT_NR; i++) {
157 if (!(sysctl_sched_features & (1UL << i)))
158 seq_puts(m, "NO_");
159 seq_printf(m, "%s ", sched_feat_names[i]);
160 }
161 seq_puts(m, "\n");
162
163 return 0;
164 }
165
166 #ifdef HAVE_JUMP_LABEL
167
168 #define jump_label_key__true STATIC_KEY_INIT_TRUE
169 #define jump_label_key__false STATIC_KEY_INIT_FALSE
170
171 #define SCHED_FEAT(name, enabled) \
172 jump_label_key__##enabled ,
173
174 struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
175 #include "features.h"
176 };
177
178 #undef SCHED_FEAT
179
180 static void sched_feat_disable(int i)
181 {
182 if (static_key_enabled(&sched_feat_keys[i]))
183 static_key_slow_dec(&sched_feat_keys[i]);
184 }
185
186 static void sched_feat_enable(int i)
187 {
188 if (!static_key_enabled(&sched_feat_keys[i]))
189 static_key_slow_inc(&sched_feat_keys[i]);
190 }
191 #else
192 static void sched_feat_disable(int i) { };
193 static void sched_feat_enable(int i) { };
194 #endif /* HAVE_JUMP_LABEL */
195
196 static int sched_feat_set(char *cmp)
197 {
198 int i;
199 int neg = 0;
200
201 if (strncmp(cmp, "NO_", 3) == 0) {
202 neg = 1;
203 cmp += 3;
204 }
205
206 for (i = 0; i < __SCHED_FEAT_NR; i++) {
207 if (strcmp(cmp, sched_feat_names[i]) == 0) {
208 if (neg) {
209 sysctl_sched_features &= ~(1UL << i);
210 sched_feat_disable(i);
211 } else {
212 sysctl_sched_features |= (1UL << i);
213 sched_feat_enable(i);
214 }
215 break;
216 }
217 }
218
219 return i;
220 }
221
222 static ssize_t
223 sched_feat_write(struct file *filp, const char __user *ubuf,
224 size_t cnt, loff_t *ppos)
225 {
226 char buf[64];
227 char *cmp;
228 int i;
229
230 if (cnt > 63)
231 cnt = 63;
232
233 if (copy_from_user(&buf, ubuf, cnt))
234 return -EFAULT;
235
236 buf[cnt] = 0;
237 cmp = strstrip(buf);
238
239 i = sched_feat_set(cmp);
240 if (i == __SCHED_FEAT_NR)
241 return -EINVAL;
242
243 *ppos += cnt;
244
245 return cnt;
246 }
247
248 static int sched_feat_open(struct inode *inode, struct file *filp)
249 {
250 return single_open(filp, sched_feat_show, NULL);
251 }
252
253 static const struct file_operations sched_feat_fops = {
254 .open = sched_feat_open,
255 .write = sched_feat_write,
256 .read = seq_read,
257 .llseek = seq_lseek,
258 .release = single_release,
259 };
260
261 static __init int sched_init_debug(void)
262 {
263 debugfs_create_file("sched_features", 0644, NULL, NULL,
264 &sched_feat_fops);
265
266 return 0;
267 }
268 late_initcall(sched_init_debug);
269 #endif /* CONFIG_SCHED_DEBUG */
270
271 /*
272 * Number of tasks to iterate in a single balance run.
273 * Limited because this is done with IRQs disabled.
274 */
275 const_debug unsigned int sysctl_sched_nr_migrate = 32;
276
277 /*
278 * period over which we average the RT time consumption, measured
279 * in ms.
280 *
281 * default: 1s
282 */
283 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
284
285 /*
286 * period over which we measure -rt task cpu usage in us.
287 * default: 1s
288 */
289 unsigned int sysctl_sched_rt_period = 1000000;
290
291 __read_mostly int scheduler_running;
292
293 /*
294 * part of the period that we allow rt tasks to run in us.
295 * default: 0.95s
296 */
297 int sysctl_sched_rt_runtime = 950000;
298
299
300
301 /*
302 * __task_rq_lock - lock the rq @p resides on.
303 */
304 static inline struct rq *__task_rq_lock(struct task_struct *p)
305 __acquires(rq->lock)
306 {
307 struct rq *rq;
308
309 lockdep_assert_held(&p->pi_lock);
310
311 for (;;) {
312 rq = task_rq(p);
313 raw_spin_lock(&rq->lock);
314 if (likely(rq == task_rq(p)))
315 return rq;
316 raw_spin_unlock(&rq->lock);
317 }
318 }
319
320 /*
321 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
322 */
323 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
324 __acquires(p->pi_lock)
325 __acquires(rq->lock)
326 {
327 struct rq *rq;
328
329 for (;;) {
330 raw_spin_lock_irqsave(&p->pi_lock, *flags);
331 rq = task_rq(p);
332 raw_spin_lock(&rq->lock);
333 if (likely(rq == task_rq(p)))
334 return rq;
335 raw_spin_unlock(&rq->lock);
336 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
337 }
338 }
339
340 static void __task_rq_unlock(struct rq *rq)
341 __releases(rq->lock)
342 {
343 raw_spin_unlock(&rq->lock);
344 }
345
346 static inline void
347 task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
348 __releases(rq->lock)
349 __releases(p->pi_lock)
350 {
351 raw_spin_unlock(&rq->lock);
352 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
353 }
354
355 /*
356 * this_rq_lock - lock this runqueue and disable interrupts.
357 */
358 static struct rq *this_rq_lock(void)
359 __acquires(rq->lock)
360 {
361 struct rq *rq;
362
363 local_irq_disable();
364 rq = this_rq();
365 raw_spin_lock(&rq->lock);
366
367 return rq;
368 }
369
370 #ifdef CONFIG_SCHED_HRTICK
371 /*
372 * Use HR-timers to deliver accurate preemption points.
373 *
374 * Its all a bit involved since we cannot program an hrt while holding the
375 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
376 * reschedule event.
377 *
378 * When we get rescheduled we reprogram the hrtick_timer outside of the
379 * rq->lock.
380 */
381
382 static void hrtick_clear(struct rq *rq)
383 {
384 if (hrtimer_active(&rq->hrtick_timer))
385 hrtimer_cancel(&rq->hrtick_timer);
386 }
387
388 /*
389 * High-resolution timer tick.
390 * Runs from hardirq context with interrupts disabled.
391 */
392 static enum hrtimer_restart hrtick(struct hrtimer *timer)
393 {
394 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
395
396 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
397
398 raw_spin_lock(&rq->lock);
399 update_rq_clock(rq);
400 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
401 raw_spin_unlock(&rq->lock);
402
403 return HRTIMER_NORESTART;
404 }
405
406 #ifdef CONFIG_SMP
407 /*
408 * called from hardirq (IPI) context
409 */
410 static void __hrtick_start(void *arg)
411 {
412 struct rq *rq = arg;
413
414 raw_spin_lock(&rq->lock);
415 hrtimer_restart(&rq->hrtick_timer);
416 rq->hrtick_csd_pending = 0;
417 raw_spin_unlock(&rq->lock);
418 }
419
420 /*
421 * Called to set the hrtick timer state.
422 *
423 * called with rq->lock held and irqs disabled
424 */
425 void hrtick_start(struct rq *rq, u64 delay)
426 {
427 struct hrtimer *timer = &rq->hrtick_timer;
428 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
429
430 hrtimer_set_expires(timer, time);
431
432 if (rq == this_rq()) {
433 hrtimer_restart(timer);
434 } else if (!rq->hrtick_csd_pending) {
435 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
436 rq->hrtick_csd_pending = 1;
437 }
438 }
439
440 static int
441 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
442 {
443 int cpu = (int)(long)hcpu;
444
445 switch (action) {
446 case CPU_UP_CANCELED:
447 case CPU_UP_CANCELED_FROZEN:
448 case CPU_DOWN_PREPARE:
449 case CPU_DOWN_PREPARE_FROZEN:
450 case CPU_DEAD:
451 case CPU_DEAD_FROZEN:
452 hrtick_clear(cpu_rq(cpu));
453 return NOTIFY_OK;
454 }
455
456 return NOTIFY_DONE;
457 }
458
459 static __init void init_hrtick(void)
460 {
461 hotcpu_notifier(hotplug_hrtick, 0);
462 }
463 #else
464 /*
465 * Called to set the hrtick timer state.
466 *
467 * called with rq->lock held and irqs disabled
468 */
469 void hrtick_start(struct rq *rq, u64 delay)
470 {
471 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
472 HRTIMER_MODE_REL_PINNED, 0);
473 }
474
475 static inline void init_hrtick(void)
476 {
477 }
478 #endif /* CONFIG_SMP */
479
480 static void init_rq_hrtick(struct rq *rq)
481 {
482 #ifdef CONFIG_SMP
483 rq->hrtick_csd_pending = 0;
484
485 rq->hrtick_csd.flags = 0;
486 rq->hrtick_csd.func = __hrtick_start;
487 rq->hrtick_csd.info = rq;
488 #endif
489
490 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
491 rq->hrtick_timer.function = hrtick;
492 }
493 #else /* CONFIG_SCHED_HRTICK */
494 static inline void hrtick_clear(struct rq *rq)
495 {
496 }
497
498 static inline void init_rq_hrtick(struct rq *rq)
499 {
500 }
501
502 static inline void init_hrtick(void)
503 {
504 }
505 #endif /* CONFIG_SCHED_HRTICK */
506
507 /*
508 * resched_task - mark a task 'to be rescheduled now'.
509 *
510 * On UP this means the setting of the need_resched flag, on SMP it
511 * might also involve a cross-CPU call to trigger the scheduler on
512 * the target CPU.
513 */
514 #ifdef CONFIG_SMP
515
516 #ifndef tsk_is_polling
517 #define tsk_is_polling(t) 0
518 #endif
519
520 void resched_task(struct task_struct *p)
521 {
522 int cpu;
523
524 assert_raw_spin_locked(&task_rq(p)->lock);
525
526 if (test_tsk_need_resched(p))
527 return;
528
529 set_tsk_need_resched(p);
530
531 cpu = task_cpu(p);
532 if (cpu == smp_processor_id())
533 return;
534
535 /* NEED_RESCHED must be visible before we test polling */
536 smp_mb();
537 if (!tsk_is_polling(p))
538 smp_send_reschedule(cpu);
539 }
540
541 void resched_cpu(int cpu)
542 {
543 struct rq *rq = cpu_rq(cpu);
544 unsigned long flags;
545
546 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
547 return;
548 resched_task(cpu_curr(cpu));
549 raw_spin_unlock_irqrestore(&rq->lock, flags);
550 }
551
552 #ifdef CONFIG_NO_HZ_COMMON
553 /*
554 * In the semi idle case, use the nearest busy cpu for migrating timers
555 * from an idle cpu. This is good for power-savings.
556 *
557 * We don't do similar optimization for completely idle system, as
558 * selecting an idle cpu will add more delays to the timers than intended
559 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
560 */
561 int get_nohz_timer_target(void)
562 {
563 int cpu = smp_processor_id();
564 int i;
565 struct sched_domain *sd;
566
567 rcu_read_lock();
568 for_each_domain(cpu, sd) {
569 for_each_cpu(i, sched_domain_span(sd)) {
570 if (!idle_cpu(i)) {
571 cpu = i;
572 goto unlock;
573 }
574 }
575 }
576 unlock:
577 rcu_read_unlock();
578 return cpu;
579 }
580 /*
581 * When add_timer_on() enqueues a timer into the timer wheel of an
582 * idle CPU then this timer might expire before the next timer event
583 * which is scheduled to wake up that CPU. In case of a completely
584 * idle system the next event might even be infinite time into the
585 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
586 * leaves the inner idle loop so the newly added timer is taken into
587 * account when the CPU goes back to idle and evaluates the timer
588 * wheel for the next timer event.
589 */
590 static void wake_up_idle_cpu(int cpu)
591 {
592 struct rq *rq = cpu_rq(cpu);
593
594 if (cpu == smp_processor_id())
595 return;
596
597 /*
598 * This is safe, as this function is called with the timer
599 * wheel base lock of (cpu) held. When the CPU is on the way
600 * to idle and has not yet set rq->curr to idle then it will
601 * be serialized on the timer wheel base lock and take the new
602 * timer into account automatically.
603 */
604 if (rq->curr != rq->idle)
605 return;
606
607 /*
608 * We can set TIF_RESCHED on the idle task of the other CPU
609 * lockless. The worst case is that the other CPU runs the
610 * idle task through an additional NOOP schedule()
611 */
612 set_tsk_need_resched(rq->idle);
613
614 /* NEED_RESCHED must be visible before we test polling */
615 smp_mb();
616 if (!tsk_is_polling(rq->idle))
617 smp_send_reschedule(cpu);
618 }
619
620 static bool wake_up_full_nohz_cpu(int cpu)
621 {
622 if (tick_nohz_full_cpu(cpu)) {
623 if (cpu != smp_processor_id() ||
624 tick_nohz_tick_stopped())
625 smp_send_reschedule(cpu);
626 return true;
627 }
628
629 return false;
630 }
631
632 void wake_up_nohz_cpu(int cpu)
633 {
634 if (!wake_up_full_nohz_cpu(cpu))
635 wake_up_idle_cpu(cpu);
636 }
637
638 static inline bool got_nohz_idle_kick(void)
639 {
640 int cpu = smp_processor_id();
641 return idle_cpu(cpu) && test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
642 }
643
644 #else /* CONFIG_NO_HZ_COMMON */
645
646 static inline bool got_nohz_idle_kick(void)
647 {
648 return false;
649 }
650
651 #endif /* CONFIG_NO_HZ_COMMON */
652
653 #ifdef CONFIG_NO_HZ_FULL
654 bool sched_can_stop_tick(void)
655 {
656 struct rq *rq;
657
658 rq = this_rq();
659
660 /* Make sure rq->nr_running update is visible after the IPI */
661 smp_rmb();
662
663 /* More than one running task need preemption */
664 if (rq->nr_running > 1)
665 return false;
666
667 return true;
668 }
669 #endif /* CONFIG_NO_HZ_FULL */
670
671 void sched_avg_update(struct rq *rq)
672 {
673 s64 period = sched_avg_period();
674
675 while ((s64)(rq->clock - rq->age_stamp) > period) {
676 /*
677 * Inline assembly required to prevent the compiler
678 * optimising this loop into a divmod call.
679 * See __iter_div_u64_rem() for another example of this.
680 */
681 asm("" : "+rm" (rq->age_stamp));
682 rq->age_stamp += period;
683 rq->rt_avg /= 2;
684 }
685 }
686
687 #else /* !CONFIG_SMP */
688 void resched_task(struct task_struct *p)
689 {
690 assert_raw_spin_locked(&task_rq(p)->lock);
691 set_tsk_need_resched(p);
692 }
693 #endif /* CONFIG_SMP */
694
695 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
696 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
697 /*
698 * Iterate task_group tree rooted at *from, calling @down when first entering a
699 * node and @up when leaving it for the final time.
700 *
701 * Caller must hold rcu_lock or sufficient equivalent.
702 */
703 int walk_tg_tree_from(struct task_group *from,
704 tg_visitor down, tg_visitor up, void *data)
705 {
706 struct task_group *parent, *child;
707 int ret;
708
709 parent = from;
710
711 down:
712 ret = (*down)(parent, data);
713 if (ret)
714 goto out;
715 list_for_each_entry_rcu(child, &parent->children, siblings) {
716 parent = child;
717 goto down;
718
719 up:
720 continue;
721 }
722 ret = (*up)(parent, data);
723 if (ret || parent == from)
724 goto out;
725
726 child = parent;
727 parent = parent->parent;
728 if (parent)
729 goto up;
730 out:
731 return ret;
732 }
733
734 int tg_nop(struct task_group *tg, void *data)
735 {
736 return 0;
737 }
738 #endif
739
740 static void set_load_weight(struct task_struct *p)
741 {
742 int prio = p->static_prio - MAX_RT_PRIO;
743 struct load_weight *load = &p->se.load;
744
745 /*
746 * SCHED_IDLE tasks get minimal weight:
747 */
748 if (p->policy == SCHED_IDLE) {
749 load->weight = scale_load(WEIGHT_IDLEPRIO);
750 load->inv_weight = WMULT_IDLEPRIO;
751 return;
752 }
753
754 load->weight = scale_load(prio_to_weight[prio]);
755 load->inv_weight = prio_to_wmult[prio];
756 }
757
758 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
759 {
760 update_rq_clock(rq);
761 sched_info_queued(p);
762 p->sched_class->enqueue_task(rq, p, flags);
763 }
764
765 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
766 {
767 update_rq_clock(rq);
768 sched_info_dequeued(p);
769 p->sched_class->dequeue_task(rq, p, flags);
770 }
771
772 void activate_task(struct rq *rq, struct task_struct *p, int flags)
773 {
774 if (task_contributes_to_load(p))
775 rq->nr_uninterruptible--;
776
777 enqueue_task(rq, p, flags);
778 }
779
780 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
781 {
782 if (task_contributes_to_load(p))
783 rq->nr_uninterruptible++;
784
785 dequeue_task(rq, p, flags);
786 }
787
788 static void update_rq_clock_task(struct rq *rq, s64 delta)
789 {
790 /*
791 * In theory, the compile should just see 0 here, and optimize out the call
792 * to sched_rt_avg_update. But I don't trust it...
793 */
794 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
795 s64 steal = 0, irq_delta = 0;
796 #endif
797 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
798 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
799
800 /*
801 * Since irq_time is only updated on {soft,}irq_exit, we might run into
802 * this case when a previous update_rq_clock() happened inside a
803 * {soft,}irq region.
804 *
805 * When this happens, we stop ->clock_task and only update the
806 * prev_irq_time stamp to account for the part that fit, so that a next
807 * update will consume the rest. This ensures ->clock_task is
808 * monotonic.
809 *
810 * It does however cause some slight miss-attribution of {soft,}irq
811 * time, a more accurate solution would be to update the irq_time using
812 * the current rq->clock timestamp, except that would require using
813 * atomic ops.
814 */
815 if (irq_delta > delta)
816 irq_delta = delta;
817
818 rq->prev_irq_time += irq_delta;
819 delta -= irq_delta;
820 #endif
821 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
822 if (static_key_false((&paravirt_steal_rq_enabled))) {
823 u64 st;
824
825 steal = paravirt_steal_clock(cpu_of(rq));
826 steal -= rq->prev_steal_time_rq;
827
828 if (unlikely(steal > delta))
829 steal = delta;
830
831 st = steal_ticks(steal);
832 steal = st * TICK_NSEC;
833
834 rq->prev_steal_time_rq += steal;
835
836 delta -= steal;
837 }
838 #endif
839
840 rq->clock_task += delta;
841
842 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
843 if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
844 sched_rt_avg_update(rq, irq_delta + steal);
845 #endif
846 }
847
848 void sched_set_stop_task(int cpu, struct task_struct *stop)
849 {
850 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
851 struct task_struct *old_stop = cpu_rq(cpu)->stop;
852
853 if (stop) {
854 /*
855 * Make it appear like a SCHED_FIFO task, its something
856 * userspace knows about and won't get confused about.
857 *
858 * Also, it will make PI more or less work without too
859 * much confusion -- but then, stop work should not
860 * rely on PI working anyway.
861 */
862 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
863
864 stop->sched_class = &stop_sched_class;
865 }
866
867 cpu_rq(cpu)->stop = stop;
868
869 if (old_stop) {
870 /*
871 * Reset it back to a normal scheduling class so that
872 * it can die in pieces.
873 */
874 old_stop->sched_class = &rt_sched_class;
875 }
876 }
877
878 /*
879 * __normal_prio - return the priority that is based on the static prio
880 */
881 static inline int __normal_prio(struct task_struct *p)
882 {
883 return p->static_prio;
884 }
885
886 /*
887 * Calculate the expected normal priority: i.e. priority
888 * without taking RT-inheritance into account. Might be
889 * boosted by interactivity modifiers. Changes upon fork,
890 * setprio syscalls, and whenever the interactivity
891 * estimator recalculates.
892 */
893 static inline int normal_prio(struct task_struct *p)
894 {
895 int prio;
896
897 if (task_has_rt_policy(p))
898 prio = MAX_RT_PRIO-1 - p->rt_priority;
899 else
900 prio = __normal_prio(p);
901 return prio;
902 }
903
904 /*
905 * Calculate the current priority, i.e. the priority
906 * taken into account by the scheduler. This value might
907 * be boosted by RT tasks, or might be boosted by
908 * interactivity modifiers. Will be RT if the task got
909 * RT-boosted. If not then it returns p->normal_prio.
910 */
911 static int effective_prio(struct task_struct *p)
912 {
913 p->normal_prio = normal_prio(p);
914 /*
915 * If we are RT tasks or we were boosted to RT priority,
916 * keep the priority unchanged. Otherwise, update priority
917 * to the normal priority:
918 */
919 if (!rt_prio(p->prio))
920 return p->normal_prio;
921 return p->prio;
922 }
923
924 /**
925 * task_curr - is this task currently executing on a CPU?
926 * @p: the task in question.
927 */
928 inline int task_curr(const struct task_struct *p)
929 {
930 return cpu_curr(task_cpu(p)) == p;
931 }
932
933 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
934 const struct sched_class *prev_class,
935 int oldprio)
936 {
937 if (prev_class != p->sched_class) {
938 if (prev_class->switched_from)
939 prev_class->switched_from(rq, p);
940 p->sched_class->switched_to(rq, p);
941 } else if (oldprio != p->prio)
942 p->sched_class->prio_changed(rq, p, oldprio);
943 }
944
945 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
946 {
947 const struct sched_class *class;
948
949 if (p->sched_class == rq->curr->sched_class) {
950 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
951 } else {
952 for_each_class(class) {
953 if (class == rq->curr->sched_class)
954 break;
955 if (class == p->sched_class) {
956 resched_task(rq->curr);
957 break;
958 }
959 }
960 }
961
962 /*
963 * A queue event has occurred, and we're going to schedule. In
964 * this case, we can save a useless back to back clock update.
965 */
966 if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
967 rq->skip_clock_update = 1;
968 }
969
970 static ATOMIC_NOTIFIER_HEAD(task_migration_notifier);
971
972 void register_task_migration_notifier(struct notifier_block *n)
973 {
974 atomic_notifier_chain_register(&task_migration_notifier, n);
975 }
976
977 #ifdef CONFIG_SMP
978 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
979 {
980 #ifdef CONFIG_SCHED_DEBUG
981 /*
982 * We should never call set_task_cpu() on a blocked task,
983 * ttwu() will sort out the placement.
984 */
985 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
986 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
987
988 #ifdef CONFIG_LOCKDEP
989 /*
990 * The caller should hold either p->pi_lock or rq->lock, when changing
991 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
992 *
993 * sched_move_task() holds both and thus holding either pins the cgroup,
994 * see task_group().
995 *
996 * Furthermore, all task_rq users should acquire both locks, see
997 * task_rq_lock().
998 */
999 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1000 lockdep_is_held(&task_rq(p)->lock)));
1001 #endif
1002 #endif
1003
1004 trace_sched_migrate_task(p, new_cpu);
1005
1006 if (task_cpu(p) != new_cpu) {
1007 struct task_migration_notifier tmn;
1008
1009 if (p->sched_class->migrate_task_rq)
1010 p->sched_class->migrate_task_rq(p, new_cpu);
1011 p->se.nr_migrations++;
1012 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
1013
1014 tmn.task = p;
1015 tmn.from_cpu = task_cpu(p);
1016 tmn.to_cpu = new_cpu;
1017
1018 atomic_notifier_call_chain(&task_migration_notifier, 0, &tmn);
1019 }
1020
1021 __set_task_cpu(p, new_cpu);
1022 }
1023
1024 struct migration_arg {
1025 struct task_struct *task;
1026 int dest_cpu;
1027 };
1028
1029 static int migration_cpu_stop(void *data);
1030
1031 /*
1032 * wait_task_inactive - wait for a thread to unschedule.
1033 *
1034 * If @match_state is nonzero, it's the @p->state value just checked and
1035 * not expected to change. If it changes, i.e. @p might have woken up,
1036 * then return zero. When we succeed in waiting for @p to be off its CPU,
1037 * we return a positive number (its total switch count). If a second call
1038 * a short while later returns the same number, the caller can be sure that
1039 * @p has remained unscheduled the whole time.
1040 *
1041 * The caller must ensure that the task *will* unschedule sometime soon,
1042 * else this function might spin for a *long* time. This function can't
1043 * be called with interrupts off, or it may introduce deadlock with
1044 * smp_call_function() if an IPI is sent by the same process we are
1045 * waiting to become inactive.
1046 */
1047 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1048 {
1049 unsigned long flags;
1050 int running, on_rq;
1051 unsigned long ncsw;
1052 struct rq *rq;
1053
1054 for (;;) {
1055 /*
1056 * We do the initial early heuristics without holding
1057 * any task-queue locks at all. We'll only try to get
1058 * the runqueue lock when things look like they will
1059 * work out!
1060 */
1061 rq = task_rq(p);
1062
1063 /*
1064 * If the task is actively running on another CPU
1065 * still, just relax and busy-wait without holding
1066 * any locks.
1067 *
1068 * NOTE! Since we don't hold any locks, it's not
1069 * even sure that "rq" stays as the right runqueue!
1070 * But we don't care, since "task_running()" will
1071 * return false if the runqueue has changed and p
1072 * is actually now running somewhere else!
1073 */
1074 while (task_running(rq, p)) {
1075 if (match_state && unlikely(p->state != match_state))
1076 return 0;
1077 cpu_relax();
1078 }
1079
1080 /*
1081 * Ok, time to look more closely! We need the rq
1082 * lock now, to be *sure*. If we're wrong, we'll
1083 * just go back and repeat.
1084 */
1085 rq = task_rq_lock(p, &flags);
1086 trace_sched_wait_task(p);
1087 running = task_running(rq, p);
1088 on_rq = p->on_rq;
1089 ncsw = 0;
1090 if (!match_state || p->state == match_state)
1091 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1092 task_rq_unlock(rq, p, &flags);
1093
1094 /*
1095 * If it changed from the expected state, bail out now.
1096 */
1097 if (unlikely(!ncsw))
1098 break;
1099
1100 /*
1101 * Was it really running after all now that we
1102 * checked with the proper locks actually held?
1103 *
1104 * Oops. Go back and try again..
1105 */
1106 if (unlikely(running)) {
1107 cpu_relax();
1108 continue;
1109 }
1110
1111 /*
1112 * It's not enough that it's not actively running,
1113 * it must be off the runqueue _entirely_, and not
1114 * preempted!
1115 *
1116 * So if it was still runnable (but just not actively
1117 * running right now), it's preempted, and we should
1118 * yield - it could be a while.
1119 */
1120 if (unlikely(on_rq)) {
1121 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1122
1123 set_current_state(TASK_UNINTERRUPTIBLE);
1124 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1125 continue;
1126 }
1127
1128 /*
1129 * Ahh, all good. It wasn't running, and it wasn't
1130 * runnable, which means that it will never become
1131 * running in the future either. We're all done!
1132 */
1133 break;
1134 }
1135
1136 return ncsw;
1137 }
1138
1139 /***
1140 * kick_process - kick a running thread to enter/exit the kernel
1141 * @p: the to-be-kicked thread
1142 *
1143 * Cause a process which is running on another CPU to enter
1144 * kernel-mode, without any delay. (to get signals handled.)
1145 *
1146 * NOTE: this function doesn't have to take the runqueue lock,
1147 * because all it wants to ensure is that the remote task enters
1148 * the kernel. If the IPI races and the task has been migrated
1149 * to another CPU then no harm is done and the purpose has been
1150 * achieved as well.
1151 */
1152 void kick_process(struct task_struct *p)
1153 {
1154 int cpu;
1155
1156 preempt_disable();
1157 cpu = task_cpu(p);
1158 if ((cpu != smp_processor_id()) && task_curr(p))
1159 smp_send_reschedule(cpu);
1160 preempt_enable();
1161 }
1162 EXPORT_SYMBOL_GPL(kick_process);
1163 #endif /* CONFIG_SMP */
1164
1165 #ifdef CONFIG_SMP
1166 /*
1167 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1168 */
1169 static int select_fallback_rq(int cpu, struct task_struct *p)
1170 {
1171 int nid = cpu_to_node(cpu);
1172 const struct cpumask *nodemask = NULL;
1173 enum { cpuset, possible, fail } state = cpuset;
1174 int dest_cpu;
1175
1176 /*
1177 * If the node that the cpu is on has been offlined, cpu_to_node()
1178 * will return -1. There is no cpu on the node, and we should
1179 * select the cpu on the other node.
1180 */
1181 if (nid != -1) {
1182 nodemask = cpumask_of_node(nid);
1183
1184 /* Look for allowed, online CPU in same node. */
1185 for_each_cpu(dest_cpu, nodemask) {
1186 if (!cpu_online(dest_cpu))
1187 continue;
1188 if (!cpu_active(dest_cpu))
1189 continue;
1190 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1191 return dest_cpu;
1192 }
1193 }
1194
1195 for (;;) {
1196 /* Any allowed, online CPU? */
1197 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1198 if (!cpu_online(dest_cpu))
1199 continue;
1200 if (!cpu_active(dest_cpu))
1201 continue;
1202 goto out;
1203 }
1204
1205 switch (state) {
1206 case cpuset:
1207 /* No more Mr. Nice Guy. */
1208 cpuset_cpus_allowed_fallback(p);
1209 state = possible;
1210 break;
1211
1212 case possible:
1213 do_set_cpus_allowed(p, cpu_possible_mask);
1214 state = fail;
1215 break;
1216
1217 case fail:
1218 BUG();
1219 break;
1220 }
1221 }
1222
1223 out:
1224 if (state != cpuset) {
1225 /*
1226 * Don't tell them about moving exiting tasks or
1227 * kernel threads (both mm NULL), since they never
1228 * leave kernel.
1229 */
1230 if (p->mm && printk_ratelimit()) {
1231 printk_sched("process %d (%s) no longer affine to cpu%d\n",
1232 task_pid_nr(p), p->comm, cpu);
1233 }
1234 }
1235
1236 return dest_cpu;
1237 }
1238
1239 /*
1240 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1241 */
1242 static inline
1243 int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
1244 {
1245 int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
1246
1247 /*
1248 * In order not to call set_task_cpu() on a blocking task we need
1249 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1250 * cpu.
1251 *
1252 * Since this is common to all placement strategies, this lives here.
1253 *
1254 * [ this allows ->select_task() to simply return task_cpu(p) and
1255 * not worry about this generic constraint ]
1256 */
1257 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1258 !cpu_online(cpu)))
1259 cpu = select_fallback_rq(task_cpu(p), p);
1260
1261 return cpu;
1262 }
1263
1264 static void update_avg(u64 *avg, u64 sample)
1265 {
1266 s64 diff = sample - *avg;
1267 *avg += diff >> 3;
1268 }
1269 #endif
1270
1271 static void
1272 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1273 {
1274 #ifdef CONFIG_SCHEDSTATS
1275 struct rq *rq = this_rq();
1276
1277 #ifdef CONFIG_SMP
1278 int this_cpu = smp_processor_id();
1279
1280 if (cpu == this_cpu) {
1281 schedstat_inc(rq, ttwu_local);
1282 schedstat_inc(p, se.statistics.nr_wakeups_local);
1283 } else {
1284 struct sched_domain *sd;
1285
1286 schedstat_inc(p, se.statistics.nr_wakeups_remote);
1287 rcu_read_lock();
1288 for_each_domain(this_cpu, sd) {
1289 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1290 schedstat_inc(sd, ttwu_wake_remote);
1291 break;
1292 }
1293 }
1294 rcu_read_unlock();
1295 }
1296
1297 if (wake_flags & WF_MIGRATED)
1298 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
1299
1300 #endif /* CONFIG_SMP */
1301
1302 schedstat_inc(rq, ttwu_count);
1303 schedstat_inc(p, se.statistics.nr_wakeups);
1304
1305 if (wake_flags & WF_SYNC)
1306 schedstat_inc(p, se.statistics.nr_wakeups_sync);
1307
1308 #endif /* CONFIG_SCHEDSTATS */
1309 }
1310
1311 static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1312 {
1313 activate_task(rq, p, en_flags);
1314 p->on_rq = 1;
1315
1316 /* if a worker is waking up, notify workqueue */
1317 if (p->flags & PF_WQ_WORKER)
1318 wq_worker_waking_up(p, cpu_of(rq));
1319 }
1320
1321 /*
1322 * Mark the task runnable and perform wakeup-preemption.
1323 */
1324 static void
1325 ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
1326 {
1327 check_preempt_curr(rq, p, wake_flags);
1328 trace_sched_wakeup(p, true);
1329
1330 p->state = TASK_RUNNING;
1331 #ifdef CONFIG_SMP
1332 if (p->sched_class->task_woken)
1333 p->sched_class->task_woken(rq, p);
1334
1335 if (rq->idle_stamp) {
1336 u64 delta = rq->clock - rq->idle_stamp;
1337 u64 max = 2*sysctl_sched_migration_cost;
1338
1339 if (delta > max)
1340 rq->avg_idle = max;
1341 else
1342 update_avg(&rq->avg_idle, delta);
1343 rq->idle_stamp = 0;
1344 }
1345 #endif
1346 }
1347
1348 static void
1349 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
1350 {
1351 #ifdef CONFIG_SMP
1352 if (p->sched_contributes_to_load)
1353 rq->nr_uninterruptible--;
1354 #endif
1355
1356 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
1357 ttwu_do_wakeup(rq, p, wake_flags);
1358 }
1359
1360 /*
1361 * Called in case the task @p isn't fully descheduled from its runqueue,
1362 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1363 * since all we need to do is flip p->state to TASK_RUNNING, since
1364 * the task is still ->on_rq.
1365 */
1366 static int ttwu_remote(struct task_struct *p, int wake_flags)
1367 {
1368 struct rq *rq;
1369 int ret = 0;
1370
1371 rq = __task_rq_lock(p);
1372 if (p->on_rq) {
1373 ttwu_do_wakeup(rq, p, wake_flags);
1374 ret = 1;
1375 }
1376 __task_rq_unlock(rq);
1377
1378 return ret;
1379 }
1380
1381 #ifdef CONFIG_SMP
1382 static void sched_ttwu_pending(void)
1383 {
1384 struct rq *rq = this_rq();
1385 struct llist_node *llist = llist_del_all(&rq->wake_list);
1386 struct task_struct *p;
1387
1388 raw_spin_lock(&rq->lock);
1389
1390 while (llist) {
1391 p = llist_entry(llist, struct task_struct, wake_entry);
1392 llist = llist_next(llist);
1393 ttwu_do_activate(rq, p, 0);
1394 }
1395
1396 raw_spin_unlock(&rq->lock);
1397 }
1398
1399 void scheduler_ipi(void)
1400 {
1401 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick()
1402 && !tick_nohz_full_cpu(smp_processor_id()))
1403 return;
1404
1405 /*
1406 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1407 * traditionally all their work was done from the interrupt return
1408 * path. Now that we actually do some work, we need to make sure
1409 * we do call them.
1410 *
1411 * Some archs already do call them, luckily irq_enter/exit nest
1412 * properly.
1413 *
1414 * Arguably we should visit all archs and update all handlers,
1415 * however a fair share of IPIs are still resched only so this would
1416 * somewhat pessimize the simple resched case.
1417 */
1418 irq_enter();
1419 tick_nohz_full_check();
1420 sched_ttwu_pending();
1421
1422 /*
1423 * Check if someone kicked us for doing the nohz idle load balance.
1424 */
1425 if (unlikely(got_nohz_idle_kick() && !need_resched())) {
1426 this_rq()->idle_balance = 1;
1427 raise_softirq_irqoff(SCHED_SOFTIRQ);
1428 }
1429 irq_exit();
1430 }
1431
1432 static void ttwu_queue_remote(struct task_struct *p, int cpu)
1433 {
1434 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list))
1435 smp_send_reschedule(cpu);
1436 }
1437
1438 bool cpus_share_cache(int this_cpu, int that_cpu)
1439 {
1440 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1441 }
1442 #endif /* CONFIG_SMP */
1443
1444 static void ttwu_queue(struct task_struct *p, int cpu)
1445 {
1446 struct rq *rq = cpu_rq(cpu);
1447
1448 #if defined(CONFIG_SMP)
1449 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1450 sched_clock_cpu(cpu); /* sync clocks x-cpu */
1451 ttwu_queue_remote(p, cpu);
1452 return;
1453 }
1454 #endif
1455
1456 raw_spin_lock(&rq->lock);
1457 ttwu_do_activate(rq, p, 0);
1458 raw_spin_unlock(&rq->lock);
1459 }
1460
1461 /**
1462 * try_to_wake_up - wake up a thread
1463 * @p: the thread to be awakened
1464 * @state: the mask of task states that can be woken
1465 * @wake_flags: wake modifier flags (WF_*)
1466 *
1467 * Put it on the run-queue if it's not already there. The "current"
1468 * thread is always on the run-queue (except when the actual
1469 * re-schedule is in progress), and as such you're allowed to do
1470 * the simpler "current->state = TASK_RUNNING" to mark yourself
1471 * runnable without the overhead of this.
1472 *
1473 * Returns %true if @p was woken up, %false if it was already running
1474 * or @state didn't match @p's state.
1475 */
1476 static int
1477 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1478 {
1479 unsigned long flags;
1480 int cpu, success = 0;
1481
1482 smp_wmb();
1483 raw_spin_lock_irqsave(&p->pi_lock, flags);
1484 if (!(p->state & state))
1485 goto out;
1486
1487 success = 1; /* we're going to change ->state */
1488 cpu = task_cpu(p);
1489
1490 if (p->on_rq && ttwu_remote(p, wake_flags))
1491 goto stat;
1492
1493 #ifdef CONFIG_SMP
1494 /*
1495 * If the owning (remote) cpu is still in the middle of schedule() with
1496 * this task as prev, wait until its done referencing the task.
1497 */
1498 while (p->on_cpu)
1499 cpu_relax();
1500 /*
1501 * Pairs with the smp_wmb() in finish_lock_switch().
1502 */
1503 smp_rmb();
1504
1505 p->sched_contributes_to_load = !!task_contributes_to_load(p);
1506 p->state = TASK_WAKING;
1507
1508 if (p->sched_class->task_waking)
1509 p->sched_class->task_waking(p);
1510
1511 cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
1512 if (task_cpu(p) != cpu) {
1513 wake_flags |= WF_MIGRATED;
1514 set_task_cpu(p, cpu);
1515 }
1516 #endif /* CONFIG_SMP */
1517
1518 ttwu_queue(p, cpu);
1519 stat:
1520 ttwu_stat(p, cpu, wake_flags);
1521 out:
1522 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1523
1524 return success;
1525 }
1526
1527 /**
1528 * try_to_wake_up_local - try to wake up a local task with rq lock held
1529 * @p: the thread to be awakened
1530 *
1531 * Put @p on the run-queue if it's not already there. The caller must
1532 * ensure that this_rq() is locked, @p is bound to this_rq() and not
1533 * the current task.
1534 */
1535 static void try_to_wake_up_local(struct task_struct *p)
1536 {
1537 struct rq *rq = task_rq(p);
1538
1539 BUG_ON(rq != this_rq());
1540 BUG_ON(p == current);
1541 lockdep_assert_held(&rq->lock);
1542
1543 if (!raw_spin_trylock(&p->pi_lock)) {
1544 raw_spin_unlock(&rq->lock);
1545 raw_spin_lock(&p->pi_lock);
1546 raw_spin_lock(&rq->lock);
1547 }
1548
1549 if (!(p->state & TASK_NORMAL))
1550 goto out;
1551
1552 if (!p->on_rq)
1553 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
1554
1555 ttwu_do_wakeup(rq, p, 0);
1556 ttwu_stat(p, smp_processor_id(), 0);
1557 out:
1558 raw_spin_unlock(&p->pi_lock);
1559 }
1560
1561 /**
1562 * wake_up_process - Wake up a specific process
1563 * @p: The process to be woken up.
1564 *
1565 * Attempt to wake up the nominated process and move it to the set of runnable
1566 * processes. Returns 1 if the process was woken up, 0 if it was already
1567 * running.
1568 *
1569 * It may be assumed that this function implies a write memory barrier before
1570 * changing the task state if and only if any tasks are woken up.
1571 */
1572 int wake_up_process(struct task_struct *p)
1573 {
1574 WARN_ON(task_is_stopped_or_traced(p));
1575 return try_to_wake_up(p, TASK_NORMAL, 0);
1576 }
1577 EXPORT_SYMBOL(wake_up_process);
1578
1579 int wake_up_state(struct task_struct *p, unsigned int state)
1580 {
1581 return try_to_wake_up(p, state, 0);
1582 }
1583
1584 /*
1585 * Perform scheduler related setup for a newly forked process p.
1586 * p is forked by current.
1587 *
1588 * __sched_fork() is basic setup used by init_idle() too:
1589 */
1590 static void __sched_fork(struct task_struct *p)
1591 {
1592 p->on_rq = 0;
1593
1594 p->se.on_rq = 0;
1595 p->se.exec_start = 0;
1596 p->se.sum_exec_runtime = 0;
1597 p->se.prev_sum_exec_runtime = 0;
1598 p->se.nr_migrations = 0;
1599 p->se.vruntime = 0;
1600 INIT_LIST_HEAD(&p->se.group_node);
1601
1602 /*
1603 * Load-tracking only depends on SMP, FAIR_GROUP_SCHED dependency below may be
1604 * removed when useful for applications beyond shares distribution (e.g.
1605 * load-balance).
1606 */
1607 #if defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)
1608 p->se.avg.runnable_avg_period = 0;
1609 p->se.avg.runnable_avg_sum = 0;
1610 #endif
1611 #ifdef CONFIG_SCHEDSTATS
1612 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
1613 #endif
1614
1615 INIT_LIST_HEAD(&p->rt.run_list);
1616
1617 #ifdef CONFIG_PREEMPT_NOTIFIERS
1618 INIT_HLIST_HEAD(&p->preempt_notifiers);
1619 #endif
1620
1621 #ifdef CONFIG_NUMA_BALANCING
1622 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
1623 p->mm->numa_next_scan = jiffies;
1624 p->mm->numa_next_reset = jiffies;
1625 p->mm->numa_scan_seq = 0;
1626 }
1627
1628 p->node_stamp = 0ULL;
1629 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
1630 p->numa_migrate_seq = p->mm ? p->mm->numa_scan_seq - 1 : 0;
1631 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
1632 p->numa_work.next = &p->numa_work;
1633 #endif /* CONFIG_NUMA_BALANCING */
1634 }
1635
1636 #ifdef CONFIG_NUMA_BALANCING
1637 #ifdef CONFIG_SCHED_DEBUG
1638 void set_numabalancing_state(bool enabled)
1639 {
1640 if (enabled)
1641 sched_feat_set("NUMA");
1642 else
1643 sched_feat_set("NO_NUMA");
1644 }
1645 #else
1646 __read_mostly bool numabalancing_enabled;
1647
1648 void set_numabalancing_state(bool enabled)
1649 {
1650 numabalancing_enabled = enabled;
1651 }
1652 #endif /* CONFIG_SCHED_DEBUG */
1653 #endif /* CONFIG_NUMA_BALANCING */
1654
1655 /*
1656 * fork()/clone()-time setup:
1657 */
1658 void sched_fork(struct task_struct *p)
1659 {
1660 unsigned long flags;
1661 int cpu = get_cpu();
1662
1663 __sched_fork(p);
1664 /*
1665 * We mark the process as running here. This guarantees that
1666 * nobody will actually run it, and a signal or other external
1667 * event cannot wake it up and insert it on the runqueue either.
1668 */
1669 p->state = TASK_RUNNING;
1670
1671 /*
1672 * Make sure we do not leak PI boosting priority to the child.
1673 */
1674 p->prio = current->normal_prio;
1675
1676 /*
1677 * Revert to default priority/policy on fork if requested.
1678 */
1679 if (unlikely(p->sched_reset_on_fork)) {
1680 if (task_has_rt_policy(p)) {
1681 p->policy = SCHED_NORMAL;
1682 p->static_prio = NICE_TO_PRIO(0);
1683 p->rt_priority = 0;
1684 } else if (PRIO_TO_NICE(p->static_prio) < 0)
1685 p->static_prio = NICE_TO_PRIO(0);
1686
1687 p->prio = p->normal_prio = __normal_prio(p);
1688 set_load_weight(p);
1689
1690 /*
1691 * We don't need the reset flag anymore after the fork. It has
1692 * fulfilled its duty:
1693 */
1694 p->sched_reset_on_fork = 0;
1695 }
1696
1697 if (!rt_prio(p->prio))
1698 p->sched_class = &fair_sched_class;
1699
1700 if (p->sched_class->task_fork)
1701 p->sched_class->task_fork(p);
1702
1703 /*
1704 * The child is not yet in the pid-hash so no cgroup attach races,
1705 * and the cgroup is pinned to this child due to cgroup_fork()
1706 * is ran before sched_fork().
1707 *
1708 * Silence PROVE_RCU.
1709 */
1710 raw_spin_lock_irqsave(&p->pi_lock, flags);
1711 set_task_cpu(p, cpu);
1712 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1713
1714 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1715 if (likely(sched_info_on()))
1716 memset(&p->sched_info, 0, sizeof(p->sched_info));
1717 #endif
1718 #if defined(CONFIG_SMP)
1719 p->on_cpu = 0;
1720 #endif
1721 #ifdef CONFIG_PREEMPT_COUNT
1722 /* Want to start with kernel preemption disabled. */
1723 task_thread_info(p)->preempt_count = 1;
1724 #endif
1725 #ifdef CONFIG_SMP
1726 plist_node_init(&p->pushable_tasks, MAX_PRIO);
1727 #endif
1728
1729 put_cpu();
1730 }
1731
1732 /*
1733 * wake_up_new_task - wake up a newly created task for the first time.
1734 *
1735 * This function will do some initial scheduler statistics housekeeping
1736 * that must be done for every newly created context, then puts the task
1737 * on the runqueue and wakes it.
1738 */
1739 void wake_up_new_task(struct task_struct *p)
1740 {
1741 unsigned long flags;
1742 struct rq *rq;
1743
1744 raw_spin_lock_irqsave(&p->pi_lock, flags);
1745 #ifdef CONFIG_SMP
1746 /*
1747 * Fork balancing, do it here and not earlier because:
1748 * - cpus_allowed can change in the fork path
1749 * - any previously selected cpu might disappear through hotplug
1750 */
1751 set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0));
1752 #endif
1753
1754 rq = __task_rq_lock(p);
1755 activate_task(rq, p, 0);
1756 p->on_rq = 1;
1757 trace_sched_wakeup_new(p, true);
1758 check_preempt_curr(rq, p, WF_FORK);
1759 #ifdef CONFIG_SMP
1760 if (p->sched_class->task_woken)
1761 p->sched_class->task_woken(rq, p);
1762 #endif
1763 task_rq_unlock(rq, p, &flags);
1764 }
1765
1766 #ifdef CONFIG_PREEMPT_NOTIFIERS
1767
1768 /**
1769 * preempt_notifier_register - tell me when current is being preempted & rescheduled
1770 * @notifier: notifier struct to register
1771 */
1772 void preempt_notifier_register(struct preempt_notifier *notifier)
1773 {
1774 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1775 }
1776 EXPORT_SYMBOL_GPL(preempt_notifier_register);
1777
1778 /**
1779 * preempt_notifier_unregister - no longer interested in preemption notifications
1780 * @notifier: notifier struct to unregister
1781 *
1782 * This is safe to call from within a preemption notifier.
1783 */
1784 void preempt_notifier_unregister(struct preempt_notifier *notifier)
1785 {
1786 hlist_del(&notifier->link);
1787 }
1788 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1789
1790 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1791 {
1792 struct preempt_notifier *notifier;
1793
1794 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
1795 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1796 }
1797
1798 static void
1799 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1800 struct task_struct *next)
1801 {
1802 struct preempt_notifier *notifier;
1803
1804 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
1805 notifier->ops->sched_out(notifier, next);
1806 }
1807
1808 #else /* !CONFIG_PREEMPT_NOTIFIERS */
1809
1810 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1811 {
1812 }
1813
1814 static void
1815 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1816 struct task_struct *next)
1817 {
1818 }
1819
1820 #endif /* CONFIG_PREEMPT_NOTIFIERS */
1821
1822 /**
1823 * prepare_task_switch - prepare to switch tasks
1824 * @rq: the runqueue preparing to switch
1825 * @prev: the current task that is being switched out
1826 * @next: the task we are going to switch to.
1827 *
1828 * This is called with the rq lock held and interrupts off. It must
1829 * be paired with a subsequent finish_task_switch after the context
1830 * switch.
1831 *
1832 * prepare_task_switch sets up locking and calls architecture specific
1833 * hooks.
1834 */
1835 static inline void
1836 prepare_task_switch(struct rq *rq, struct task_struct *prev,
1837 struct task_struct *next)
1838 {
1839 trace_sched_switch(prev, next);
1840 sched_info_switch(prev, next);
1841 perf_event_task_sched_out(prev, next);
1842 fire_sched_out_preempt_notifiers(prev, next);
1843 prepare_lock_switch(rq, next);
1844 prepare_arch_switch(next);
1845 }
1846
1847 /**
1848 * finish_task_switch - clean up after a task-switch
1849 * @rq: runqueue associated with task-switch
1850 * @prev: the thread we just switched away from.
1851 *
1852 * finish_task_switch must be called after the context switch, paired
1853 * with a prepare_task_switch call before the context switch.
1854 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1855 * and do any other architecture-specific cleanup actions.
1856 *
1857 * Note that we may have delayed dropping an mm in context_switch(). If
1858 * so, we finish that here outside of the runqueue lock. (Doing it
1859 * with the lock held can cause deadlocks; see schedule() for
1860 * details.)
1861 */
1862 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
1863 __releases(rq->lock)
1864 {
1865 struct mm_struct *mm = rq->prev_mm;
1866 long prev_state;
1867
1868 rq->prev_mm = NULL;
1869
1870 /*
1871 * A task struct has one reference for the use as "current".
1872 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
1873 * schedule one last time. The schedule call will never return, and
1874 * the scheduled task must drop that reference.
1875 * The test for TASK_DEAD must occur while the runqueue locks are
1876 * still held, otherwise prev could be scheduled on another cpu, die
1877 * there before we look at prev->state, and then the reference would
1878 * be dropped twice.
1879 * Manfred Spraul <manfred@colorfullife.com>
1880 */
1881 prev_state = prev->state;
1882 vtime_task_switch(prev);
1883 finish_arch_switch(prev);
1884 perf_event_task_sched_in(prev, current);
1885 finish_lock_switch(rq, prev);
1886 finish_arch_post_lock_switch();
1887
1888 fire_sched_in_preempt_notifiers(current);
1889 if (mm)
1890 mmdrop(mm);
1891 if (unlikely(prev_state == TASK_DEAD)) {
1892 /*
1893 * Remove function-return probe instances associated with this
1894 * task and put them back on the free list.
1895 */
1896 kprobe_flush_task(prev);
1897 put_task_struct(prev);
1898 }
1899 }
1900
1901 #ifdef CONFIG_SMP
1902
1903 /* assumes rq->lock is held */
1904 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
1905 {
1906 if (prev->sched_class->pre_schedule)
1907 prev->sched_class->pre_schedule(rq, prev);
1908 }
1909
1910 /* rq->lock is NOT held, but preemption is disabled */
1911 static inline void post_schedule(struct rq *rq)
1912 {
1913 if (rq->post_schedule) {
1914 unsigned long flags;
1915
1916 raw_spin_lock_irqsave(&rq->lock, flags);
1917 if (rq->curr->sched_class->post_schedule)
1918 rq->curr->sched_class->post_schedule(rq);
1919 raw_spin_unlock_irqrestore(&rq->lock, flags);
1920
1921 rq->post_schedule = 0;
1922 }
1923 }
1924
1925 #else
1926
1927 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
1928 {
1929 }
1930
1931 static inline void post_schedule(struct rq *rq)
1932 {
1933 }
1934
1935 #endif
1936
1937 /**
1938 * schedule_tail - first thing a freshly forked thread must call.
1939 * @prev: the thread we just switched away from.
1940 */
1941 asmlinkage void schedule_tail(struct task_struct *prev)
1942 __releases(rq->lock)
1943 {
1944 struct rq *rq = this_rq();
1945
1946 finish_task_switch(rq, prev);
1947
1948 /*
1949 * FIXME: do we need to worry about rq being invalidated by the
1950 * task_switch?
1951 */
1952 post_schedule(rq);
1953
1954 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1955 /* In this case, finish_task_switch does not reenable preemption */
1956 preempt_enable();
1957 #endif
1958 if (current->set_child_tid)
1959 put_user(task_pid_vnr(current), current->set_child_tid);
1960 }
1961
1962 /*
1963 * context_switch - switch to the new MM and the new
1964 * thread's register state.
1965 */
1966 static inline void
1967 context_switch(struct rq *rq, struct task_struct *prev,
1968 struct task_struct *next)
1969 {
1970 struct mm_struct *mm, *oldmm;
1971
1972 prepare_task_switch(rq, prev, next);
1973
1974 mm = next->mm;
1975 oldmm = prev->active_mm;
1976 /*
1977 * For paravirt, this is coupled with an exit in switch_to to
1978 * combine the page table reload and the switch backend into
1979 * one hypercall.
1980 */
1981 arch_start_context_switch(prev);
1982
1983 if (!mm) {
1984 next->active_mm = oldmm;
1985 atomic_inc(&oldmm->mm_count);
1986 enter_lazy_tlb(oldmm, next);
1987 } else
1988 switch_mm(oldmm, mm, next);
1989
1990 if (!prev->mm) {
1991 prev->active_mm = NULL;
1992 rq->prev_mm = oldmm;
1993 }
1994 /*
1995 * Since the runqueue lock will be released by the next
1996 * task (which is an invalid locking op but in the case
1997 * of the scheduler it's an obvious special-case), so we
1998 * do an early lockdep release here:
1999 */
2000 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2001 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2002 #endif
2003
2004 context_tracking_task_switch(prev, next);
2005 /* Here we just switch the register state and the stack. */
2006 switch_to(prev, next, prev);
2007
2008 barrier();
2009 /*
2010 * this_rq must be evaluated again because prev may have moved
2011 * CPUs since it called schedule(), thus the 'rq' on its stack
2012 * frame will be invalid.
2013 */
2014 finish_task_switch(this_rq(), prev);
2015 }
2016
2017 /*
2018 * nr_running and nr_context_switches:
2019 *
2020 * externally visible scheduler statistics: current number of runnable
2021 * threads, total number of context switches performed since bootup.
2022 */
2023 unsigned long nr_running(void)
2024 {
2025 unsigned long i, sum = 0;
2026
2027 for_each_online_cpu(i)
2028 sum += cpu_rq(i)->nr_running;
2029
2030 return sum;
2031 }
2032
2033 unsigned long long nr_context_switches(void)
2034 {
2035 int i;
2036 unsigned long long sum = 0;
2037
2038 for_each_possible_cpu(i)
2039 sum += cpu_rq(i)->nr_switches;
2040
2041 return sum;
2042 }
2043
2044 unsigned long nr_iowait(void)
2045 {
2046 unsigned long i, sum = 0;
2047
2048 for_each_possible_cpu(i)
2049 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2050
2051 return sum;
2052 }
2053
2054 unsigned long nr_iowait_cpu(int cpu)
2055 {
2056 struct rq *this = cpu_rq(cpu);
2057 return atomic_read(&this->nr_iowait);
2058 }
2059
2060 unsigned long this_cpu_load(void)
2061 {
2062 struct rq *this = this_rq();
2063 return this->cpu_load[0];
2064 }
2065
2066
2067 /*
2068 * Global load-average calculations
2069 *
2070 * We take a distributed and async approach to calculating the global load-avg
2071 * in order to minimize overhead.
2072 *
2073 * The global load average is an exponentially decaying average of nr_running +
2074 * nr_uninterruptible.
2075 *
2076 * Once every LOAD_FREQ:
2077 *
2078 * nr_active = 0;
2079 * for_each_possible_cpu(cpu)
2080 * nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible;
2081 *
2082 * avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n)
2083 *
2084 * Due to a number of reasons the above turns in the mess below:
2085 *
2086 * - for_each_possible_cpu() is prohibitively expensive on machines with
2087 * serious number of cpus, therefore we need to take a distributed approach
2088 * to calculating nr_active.
2089 *
2090 * \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0
2091 * = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) }
2092 *
2093 * So assuming nr_active := 0 when we start out -- true per definition, we
2094 * can simply take per-cpu deltas and fold those into a global accumulate
2095 * to obtain the same result. See calc_load_fold_active().
2096 *
2097 * Furthermore, in order to avoid synchronizing all per-cpu delta folding
2098 * across the machine, we assume 10 ticks is sufficient time for every
2099 * cpu to have completed this task.
2100 *
2101 * This places an upper-bound on the IRQ-off latency of the machine. Then
2102 * again, being late doesn't loose the delta, just wrecks the sample.
2103 *
2104 * - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because
2105 * this would add another cross-cpu cacheline miss and atomic operation
2106 * to the wakeup path. Instead we increment on whatever cpu the task ran
2107 * when it went into uninterruptible state and decrement on whatever cpu
2108 * did the wakeup. This means that only the sum of nr_uninterruptible over
2109 * all cpus yields the correct result.
2110 *
2111 * This covers the NO_HZ=n code, for extra head-aches, see the comment below.
2112 */
2113
2114 /* Variables and functions for calc_load */
2115 static atomic_long_t calc_load_tasks;
2116 static unsigned long calc_load_update;
2117 unsigned long avenrun[3];
2118 EXPORT_SYMBOL(avenrun); /* should be removed */
2119
2120 /**
2121 * get_avenrun - get the load average array
2122 * @loads: pointer to dest load array
2123 * @offset: offset to add
2124 * @shift: shift count to shift the result left
2125 *
2126 * These values are estimates at best, so no need for locking.
2127 */
2128 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
2129 {
2130 loads[0] = (avenrun[0] + offset) << shift;
2131 loads[1] = (avenrun[1] + offset) << shift;
2132 loads[2] = (avenrun[2] + offset) << shift;
2133 }
2134
2135 static long calc_load_fold_active(struct rq *this_rq)
2136 {
2137 long nr_active, delta = 0;
2138
2139 nr_active = this_rq->nr_running;
2140 nr_active += (long) this_rq->nr_uninterruptible;
2141
2142 if (nr_active != this_rq->calc_load_active) {
2143 delta = nr_active - this_rq->calc_load_active;
2144 this_rq->calc_load_active = nr_active;
2145 }
2146
2147 return delta;
2148 }
2149
2150 /*
2151 * a1 = a0 * e + a * (1 - e)
2152 */
2153 static unsigned long
2154 calc_load(unsigned long load, unsigned long exp, unsigned long active)
2155 {
2156 load *= exp;
2157 load += active * (FIXED_1 - exp);
2158 load += 1UL << (FSHIFT - 1);
2159 return load >> FSHIFT;
2160 }
2161
2162 #ifdef CONFIG_NO_HZ_COMMON
2163 /*
2164 * Handle NO_HZ for the global load-average.
2165 *
2166 * Since the above described distributed algorithm to compute the global
2167 * load-average relies on per-cpu sampling from the tick, it is affected by
2168 * NO_HZ.
2169 *
2170 * The basic idea is to fold the nr_active delta into a global idle-delta upon
2171 * entering NO_HZ state such that we can include this as an 'extra' cpu delta
2172 * when we read the global state.
2173 *
2174 * Obviously reality has to ruin such a delightfully simple scheme:
2175 *
2176 * - When we go NO_HZ idle during the window, we can negate our sample
2177 * contribution, causing under-accounting.
2178 *
2179 * We avoid this by keeping two idle-delta counters and flipping them
2180 * when the window starts, thus separating old and new NO_HZ load.
2181 *
2182 * The only trick is the slight shift in index flip for read vs write.
2183 *
2184 * 0s 5s 10s 15s
2185 * +10 +10 +10 +10
2186 * |-|-----------|-|-----------|-|-----------|-|
2187 * r:0 0 1 1 0 0 1 1 0
2188 * w:0 1 1 0 0 1 1 0 0
2189 *
2190 * This ensures we'll fold the old idle contribution in this window while
2191 * accumlating the new one.
2192 *
2193 * - When we wake up from NO_HZ idle during the window, we push up our
2194 * contribution, since we effectively move our sample point to a known
2195 * busy state.
2196 *
2197 * This is solved by pushing the window forward, and thus skipping the
2198 * sample, for this cpu (effectively using the idle-delta for this cpu which
2199 * was in effect at the time the window opened). This also solves the issue
2200 * of having to deal with a cpu having been in NOHZ idle for multiple
2201 * LOAD_FREQ intervals.
2202 *
2203 * When making the ILB scale, we should try to pull this in as well.
2204 */
2205 static atomic_long_t calc_load_idle[2];
2206 static int calc_load_idx;
2207
2208 static inline int calc_load_write_idx(void)
2209 {
2210 int idx = calc_load_idx;
2211
2212 /*
2213 * See calc_global_nohz(), if we observe the new index, we also
2214 * need to observe the new update time.
2215 */
2216 smp_rmb();
2217
2218 /*
2219 * If the folding window started, make sure we start writing in the
2220 * next idle-delta.
2221 */
2222 if (!time_before(jiffies, calc_load_update))
2223 idx++;
2224
2225 return idx & 1;
2226 }
2227
2228 static inline int calc_load_read_idx(void)
2229 {
2230 return calc_load_idx & 1;
2231 }
2232
2233 void calc_load_enter_idle(void)
2234 {
2235 struct rq *this_rq = this_rq();
2236 long delta;
2237
2238 /*
2239 * We're going into NOHZ mode, if there's any pending delta, fold it
2240 * into the pending idle delta.
2241 */
2242 delta = calc_load_fold_active(this_rq);
2243 if (delta) {
2244 int idx = calc_load_write_idx();
2245 atomic_long_add(delta, &calc_load_idle[idx]);
2246 }
2247 }
2248
2249 void calc_load_exit_idle(void)
2250 {
2251 struct rq *this_rq = this_rq();
2252
2253 /*
2254 * If we're still before the sample window, we're done.
2255 */
2256 if (time_before(jiffies, this_rq->calc_load_update))
2257 return;
2258
2259 /*
2260 * We woke inside or after the sample window, this means we're already
2261 * accounted through the nohz accounting, so skip the entire deal and
2262 * sync up for the next window.
2263 */
2264 this_rq->calc_load_update = calc_load_update;
2265 if (time_before(jiffies, this_rq->calc_load_update + 10))
2266 this_rq->calc_load_update += LOAD_FREQ;
2267 }
2268
2269 static long calc_load_fold_idle(void)
2270 {
2271 int idx = calc_load_read_idx();
2272 long delta = 0;
2273
2274 if (atomic_long_read(&calc_load_idle[idx]))
2275 delta = atomic_long_xchg(&calc_load_idle[idx], 0);
2276
2277 return delta;
2278 }
2279
2280 /**
2281 * fixed_power_int - compute: x^n, in O(log n) time
2282 *
2283 * @x: base of the power
2284 * @frac_bits: fractional bits of @x
2285 * @n: power to raise @x to.
2286 *
2287 * By exploiting the relation between the definition of the natural power
2288 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
2289 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
2290 * (where: n_i \elem {0, 1}, the binary vector representing n),
2291 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
2292 * of course trivially computable in O(log_2 n), the length of our binary
2293 * vector.
2294 */
2295 static unsigned long
2296 fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
2297 {
2298 unsigned long result = 1UL << frac_bits;
2299
2300 if (n) for (;;) {
2301 if (n & 1) {
2302 result *= x;
2303 result += 1UL << (frac_bits - 1);
2304 result >>= frac_bits;
2305 }
2306 n >>= 1;
2307 if (!n)
2308 break;
2309 x *= x;
2310 x += 1UL << (frac_bits - 1);
2311 x >>= frac_bits;
2312 }
2313
2314 return result;
2315 }
2316
2317 /*
2318 * a1 = a0 * e + a * (1 - e)
2319 *
2320 * a2 = a1 * e + a * (1 - e)
2321 * = (a0 * e + a * (1 - e)) * e + a * (1 - e)
2322 * = a0 * e^2 + a * (1 - e) * (1 + e)
2323 *
2324 * a3 = a2 * e + a * (1 - e)
2325 * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
2326 * = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
2327 *
2328 * ...
2329 *
2330 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
2331 * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
2332 * = a0 * e^n + a * (1 - e^n)
2333 *
2334 * [1] application of the geometric series:
2335 *
2336 * n 1 - x^(n+1)
2337 * S_n := \Sum x^i = -------------
2338 * i=0 1 - x
2339 */
2340 static unsigned long
2341 calc_load_n(unsigned long load, unsigned long exp,
2342 unsigned long active, unsigned int n)
2343 {
2344
2345 return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
2346 }
2347
2348 /*
2349 * NO_HZ can leave us missing all per-cpu ticks calling
2350 * calc_load_account_active(), but since an idle CPU folds its delta into
2351 * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
2352 * in the pending idle delta if our idle period crossed a load cycle boundary.
2353 *
2354 * Once we've updated the global active value, we need to apply the exponential
2355 * weights adjusted to the number of cycles missed.
2356 */
2357 static void calc_global_nohz(void)
2358 {
2359 long delta, active, n;
2360
2361 if (!time_before(jiffies, calc_load_update + 10)) {
2362 /*
2363 * Catch-up, fold however many we are behind still
2364 */
2365 delta = jiffies - calc_load_update - 10;
2366 n = 1 + (delta / LOAD_FREQ);
2367
2368 active = atomic_long_read(&calc_load_tasks);
2369 active = active > 0 ? active * FIXED_1 : 0;
2370
2371 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
2372 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
2373 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
2374
2375 calc_load_update += n * LOAD_FREQ;
2376 }
2377
2378 /*
2379 * Flip the idle index...
2380 *
2381 * Make sure we first write the new time then flip the index, so that
2382 * calc_load_write_idx() will see the new time when it reads the new
2383 * index, this avoids a double flip messing things up.
2384 */
2385 smp_wmb();
2386 calc_load_idx++;
2387 }
2388 #else /* !CONFIG_NO_HZ_COMMON */
2389
2390 static inline long calc_load_fold_idle(void) { return 0; }
2391 static inline void calc_global_nohz(void) { }
2392
2393 #endif /* CONFIG_NO_HZ_COMMON */
2394
2395 /*
2396 * calc_load - update the avenrun load estimates 10 ticks after the
2397 * CPUs have updated calc_load_tasks.
2398 */
2399 void calc_global_load(unsigned long ticks)
2400 {
2401 long active, delta;
2402
2403 if (time_before(jiffies, calc_load_update + 10))
2404 return;
2405
2406 /*
2407 * Fold the 'old' idle-delta to include all NO_HZ cpus.
2408 */
2409 delta = calc_load_fold_idle();
2410 if (delta)
2411 atomic_long_add(delta, &calc_load_tasks);
2412
2413 active = atomic_long_read(&calc_load_tasks);
2414 active = active > 0 ? active * FIXED_1 : 0;
2415
2416 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
2417 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
2418 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
2419
2420 calc_load_update += LOAD_FREQ;
2421
2422 /*
2423 * In case we idled for multiple LOAD_FREQ intervals, catch up in bulk.
2424 */
2425 calc_global_nohz();
2426 }
2427
2428 /*
2429 * Called from update_cpu_load() to periodically update this CPU's
2430 * active count.
2431 */
2432 static void calc_load_account_active(struct rq *this_rq)
2433 {
2434 long delta;
2435
2436 if (time_before(jiffies, this_rq->calc_load_update))
2437 return;
2438
2439 delta = calc_load_fold_active(this_rq);
2440 if (delta)
2441 atomic_long_add(delta, &calc_load_tasks);
2442
2443 this_rq->calc_load_update += LOAD_FREQ;
2444 }
2445
2446 /*
2447 * End of global load-average stuff
2448 */
2449
2450 /*
2451 * The exact cpuload at various idx values, calculated at every tick would be
2452 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
2453 *
2454 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
2455 * on nth tick when cpu may be busy, then we have:
2456 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2457 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
2458 *
2459 * decay_load_missed() below does efficient calculation of
2460 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
2461 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
2462 *
2463 * The calculation is approximated on a 128 point scale.
2464 * degrade_zero_ticks is the number of ticks after which load at any
2465 * particular idx is approximated to be zero.
2466 * degrade_factor is a precomputed table, a row for each load idx.
2467 * Each column corresponds to degradation factor for a power of two ticks,
2468 * based on 128 point scale.
2469 * Example:
2470 * row 2, col 3 (=12) says that the degradation at load idx 2 after
2471 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
2472 *
2473 * With this power of 2 load factors, we can degrade the load n times
2474 * by looking at 1 bits in n and doing as many mult/shift instead of
2475 * n mult/shifts needed by the exact degradation.
2476 */
2477 #define DEGRADE_SHIFT 7
2478 static const unsigned char
2479 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
2480 static const unsigned char
2481 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
2482 {0, 0, 0, 0, 0, 0, 0, 0},
2483 {64, 32, 8, 0, 0, 0, 0, 0},
2484 {96, 72, 40, 12, 1, 0, 0},
2485 {112, 98, 75, 43, 15, 1, 0},
2486 {120, 112, 98, 76, 45, 16, 2} };
2487
2488 /*
2489 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
2490 * would be when CPU is idle and so we just decay the old load without
2491 * adding any new load.
2492 */
2493 static unsigned long
2494 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
2495 {
2496 int j = 0;
2497
2498 if (!missed_updates)
2499 return load;
2500
2501 if (missed_updates >= degrade_zero_ticks[idx])
2502 return 0;
2503
2504 if (idx == 1)
2505 return load >> missed_updates;
2506
2507 while (missed_updates) {
2508 if (missed_updates % 2)
2509 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
2510
2511 missed_updates >>= 1;
2512 j++;
2513 }
2514 return load;
2515 }
2516
2517 /*
2518 * Update rq->cpu_load[] statistics. This function is usually called every
2519 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
2520 * every tick. We fix it up based on jiffies.
2521 */
2522 static void __update_cpu_load(struct rq *this_rq, unsigned long this_load,
2523 unsigned long pending_updates)
2524 {
2525 int i, scale;
2526
2527 this_rq->nr_load_updates++;
2528
2529 /* Update our load: */
2530 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
2531 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2532 unsigned long old_load, new_load;
2533
2534 /* scale is effectively 1 << i now, and >> i divides by scale */
2535
2536 old_load = this_rq->cpu_load[i];
2537 old_load = decay_load_missed(old_load, pending_updates - 1, i);
2538 new_load = this_load;
2539 /*
2540 * Round up the averaging division if load is increasing. This
2541 * prevents us from getting stuck on 9 if the load is 10, for
2542 * example.
2543 */
2544 if (new_load > old_load)
2545 new_load += scale - 1;
2546
2547 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
2548 }
2549
2550 sched_avg_update(this_rq);
2551 }
2552
2553 #ifdef CONFIG_NO_HZ_COMMON
2554 /*
2555 * There is no sane way to deal with nohz on smp when using jiffies because the
2556 * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading
2557 * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
2558 *
2559 * Therefore we cannot use the delta approach from the regular tick since that
2560 * would seriously skew the load calculation. However we'll make do for those
2561 * updates happening while idle (nohz_idle_balance) or coming out of idle
2562 * (tick_nohz_idle_exit).
2563 *
2564 * This means we might still be one tick off for nohz periods.
2565 */
2566
2567 /*
2568 * Called from nohz_idle_balance() to update the load ratings before doing the
2569 * idle balance.
2570 */
2571 void update_idle_cpu_load(struct rq *this_rq)
2572 {
2573 unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
2574 unsigned long load = this_rq->load.weight;
2575 unsigned long pending_updates;
2576
2577 /*
2578 * bail if there's load or we're actually up-to-date.
2579 */
2580 if (load || curr_jiffies == this_rq->last_load_update_tick)
2581 return;
2582
2583 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2584 this_rq->last_load_update_tick = curr_jiffies;
2585
2586 __update_cpu_load(this_rq, load, pending_updates);
2587 }
2588
2589 /*
2590 * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed.
2591 */
2592 void update_cpu_load_nohz(void)
2593 {
2594 struct rq *this_rq = this_rq();
2595 unsigned long curr_jiffies = ACCESS_ONCE(jiffies);
2596 unsigned long pending_updates;
2597
2598 if (curr_jiffies == this_rq->last_load_update_tick)
2599 return;
2600
2601 raw_spin_lock(&this_rq->lock);
2602 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
2603 if (pending_updates) {
2604 this_rq->last_load_update_tick = curr_jiffies;
2605 /*
2606 * We were idle, this means load 0, the current load might be
2607 * !0 due to remote wakeups and the sort.
2608 */
2609 __update_cpu_load(this_rq, 0, pending_updates);
2610 }
2611 raw_spin_unlock(&this_rq->lock);
2612 }
2613 #endif /* CONFIG_NO_HZ_COMMON */
2614
2615 /*
2616 * Called from scheduler_tick()
2617 */
2618 static void update_cpu_load_active(struct rq *this_rq)
2619 {
2620 /*
2621 * See the mess around update_idle_cpu_load() / update_cpu_load_nohz().
2622 */
2623 this_rq->last_load_update_tick = jiffies;
2624 __update_cpu_load(this_rq, this_rq->load.weight, 1);
2625
2626 calc_load_account_active(this_rq);
2627 }
2628
2629 #ifdef CONFIG_SMP
2630
2631 /*
2632 * sched_exec - execve() is a valuable balancing opportunity, because at
2633 * this point the task has the smallest effective memory and cache footprint.
2634 */
2635 void sched_exec(void)
2636 {
2637 struct task_struct *p = current;
2638 unsigned long flags;
2639 int dest_cpu;
2640
2641 raw_spin_lock_irqsave(&p->pi_lock, flags);
2642 dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0);
2643 if (dest_cpu == smp_processor_id())
2644 goto unlock;
2645
2646 if (likely(cpu_active(dest_cpu))) {
2647 struct migration_arg arg = { p, dest_cpu };
2648
2649 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2650 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2651 return;
2652 }
2653 unlock:
2654 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2655 }
2656
2657 #endif
2658
2659 DEFINE_PER_CPU(struct kernel_stat, kstat);
2660 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2661
2662 EXPORT_PER_CPU_SYMBOL(kstat);
2663 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
2664
2665 /*
2666 * Return any ns on the sched_clock that have not yet been accounted in
2667 * @p in case that task is currently running.
2668 *
2669 * Called with task_rq_lock() held on @rq.
2670 */
2671 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
2672 {
2673 u64 ns = 0;
2674
2675 if (task_current(rq, p)) {
2676 update_rq_clock(rq);
2677 ns = rq->clock_task - p->se.exec_start;
2678 if ((s64)ns < 0)
2679 ns = 0;
2680 }
2681
2682 return ns;
2683 }
2684
2685 unsigned long long task_delta_exec(struct task_struct *p)
2686 {
2687 unsigned long flags;
2688 struct rq *rq;
2689 u64 ns = 0;
2690
2691 rq = task_rq_lock(p, &flags);
2692 ns = do_task_delta_exec(p, rq);
2693 task_rq_unlock(rq, p, &flags);
2694
2695 return ns;
2696 }
2697
2698 /*
2699 * Return accounted runtime for the task.
2700 * In case the task is currently running, return the runtime plus current's
2701 * pending runtime that have not been accounted yet.
2702 */
2703 unsigned long long task_sched_runtime(struct task_struct *p)
2704 {
2705 unsigned long flags;
2706 struct rq *rq;
2707 u64 ns = 0;
2708
2709 rq = task_rq_lock(p, &flags);
2710 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
2711 task_rq_unlock(rq, p, &flags);
2712
2713 return ns;
2714 }
2715
2716 /*
2717 * This function gets called by the timer code, with HZ frequency.
2718 * We call it with interrupts disabled.
2719 */
2720 void scheduler_tick(void)
2721 {
2722 int cpu = smp_processor_id();
2723 struct rq *rq = cpu_rq(cpu);
2724 struct task_struct *curr = rq->curr;
2725
2726 sched_clock_tick();
2727
2728 raw_spin_lock(&rq->lock);
2729 update_rq_clock(rq);
2730 update_cpu_load_active(rq);
2731 curr->sched_class->task_tick(rq, curr, 0);
2732 raw_spin_unlock(&rq->lock);
2733
2734 perf_event_task_tick();
2735
2736 #ifdef CONFIG_SMP
2737 rq->idle_balance = idle_cpu(cpu);
2738 trigger_load_balance(rq, cpu);
2739 #endif
2740 }
2741
2742 notrace unsigned long get_parent_ip(unsigned long addr)
2743 {
2744 if (in_lock_functions(addr)) {
2745 addr = CALLER_ADDR2;
2746 if (in_lock_functions(addr))
2747 addr = CALLER_ADDR3;
2748 }
2749 return addr;
2750 }
2751
2752 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
2753 defined(CONFIG_PREEMPT_TRACER))
2754
2755 void __kprobes add_preempt_count(int val)
2756 {
2757 #ifdef CONFIG_DEBUG_PREEMPT
2758 /*
2759 * Underflow?
2760 */
2761 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
2762 return;
2763 #endif
2764 preempt_count() += val;
2765 #ifdef CONFIG_DEBUG_PREEMPT
2766 /*
2767 * Spinlock count overflowing soon?
2768 */
2769 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
2770 PREEMPT_MASK - 10);
2771 #endif
2772 if (preempt_count() == val)
2773 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
2774 }
2775 EXPORT_SYMBOL(add_preempt_count);
2776
2777 void __kprobes sub_preempt_count(int val)
2778 {
2779 #ifdef CONFIG_DEBUG_PREEMPT
2780 /*
2781 * Underflow?
2782 */
2783 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
2784 return;
2785 /*
2786 * Is the spinlock portion underflowing?
2787 */
2788 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
2789 !(preempt_count() & PREEMPT_MASK)))
2790 return;
2791 #endif
2792
2793 if (preempt_count() == val)
2794 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
2795 preempt_count() -= val;
2796 }
2797 EXPORT_SYMBOL(sub_preempt_count);
2798
2799 #endif
2800
2801 /*
2802 * Print scheduling while atomic bug:
2803 */
2804 static noinline void __schedule_bug(struct task_struct *prev)
2805 {
2806 if (oops_in_progress)
2807 return;
2808
2809 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
2810 prev->comm, prev->pid, preempt_count());
2811
2812 debug_show_held_locks(prev);
2813 print_modules();
2814 if (irqs_disabled())
2815 print_irqtrace_events(prev);
2816 dump_stack();
2817 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
2818 }
2819
2820 /*
2821 * Various schedule()-time debugging checks and statistics:
2822 */
2823 static inline void schedule_debug(struct task_struct *prev)
2824 {
2825 /*
2826 * Test if we are atomic. Since do_exit() needs to call into
2827 * schedule() atomically, we ignore that path for now.
2828 * Otherwise, whine if we are scheduling when we should not be.
2829 */
2830 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
2831 __schedule_bug(prev);
2832 rcu_sleep_check();
2833
2834 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2835
2836 schedstat_inc(this_rq(), sched_count);
2837 }
2838
2839 static void put_prev_task(struct rq *rq, struct task_struct *prev)
2840 {
2841 if (prev->on_rq || rq->skip_clock_update < 0)
2842 update_rq_clock(rq);
2843 prev->sched_class->put_prev_task(rq, prev);
2844 }
2845
2846 /*
2847 * Pick up the highest-prio task:
2848 */
2849 static inline struct task_struct *
2850 pick_next_task(struct rq *rq)
2851 {
2852 const struct sched_class *class;
2853 struct task_struct *p;
2854
2855 /*
2856 * Optimization: we know that if all tasks are in
2857 * the fair class we can call that function directly:
2858 */
2859 if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
2860 p = fair_sched_class.pick_next_task(rq);
2861 if (likely(p))
2862 return p;
2863 }
2864
2865 for_each_class(class) {
2866 p = class->pick_next_task(rq);
2867 if (p)
2868 return p;
2869 }
2870
2871 BUG(); /* the idle class will always have a runnable task */
2872 }
2873
2874 /*
2875 * __schedule() is the main scheduler function.
2876 *
2877 * The main means of driving the scheduler and thus entering this function are:
2878 *
2879 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
2880 *
2881 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
2882 * paths. For example, see arch/x86/entry_64.S.
2883 *
2884 * To drive preemption between tasks, the scheduler sets the flag in timer
2885 * interrupt handler scheduler_tick().
2886 *
2887 * 3. Wakeups don't really cause entry into schedule(). They add a
2888 * task to the run-queue and that's it.
2889 *
2890 * Now, if the new task added to the run-queue preempts the current
2891 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
2892 * called on the nearest possible occasion:
2893 *
2894 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
2895 *
2896 * - in syscall or exception context, at the next outmost
2897 * preempt_enable(). (this might be as soon as the wake_up()'s
2898 * spin_unlock()!)
2899 *
2900 * - in IRQ context, return from interrupt-handler to
2901 * preemptible context
2902 *
2903 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
2904 * then at the next:
2905 *
2906 * - cond_resched() call
2907 * - explicit schedule() call
2908 * - return from syscall or exception to user-space
2909 * - return from interrupt-handler to user-space
2910 */
2911 static void __sched __schedule(void)
2912 {
2913 struct task_struct *prev, *next;
2914 unsigned long *switch_count;
2915 struct rq *rq;
2916 int cpu;
2917
2918 need_resched:
2919 preempt_disable();
2920 cpu = smp_processor_id();
2921 rq = cpu_rq(cpu);
2922 rcu_note_context_switch(cpu);
2923 prev = rq->curr;
2924
2925 schedule_debug(prev);
2926
2927 if (sched_feat(HRTICK))
2928 hrtick_clear(rq);
2929
2930 raw_spin_lock_irq(&rq->lock);
2931
2932 switch_count = &prev->nivcsw;
2933 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2934 if (unlikely(signal_pending_state(prev->state, prev))) {
2935 prev->state = TASK_RUNNING;
2936 } else {
2937 deactivate_task(rq, prev, DEQUEUE_SLEEP);
2938 prev->on_rq = 0;
2939
2940 /*
2941 * If a worker went to sleep, notify and ask workqueue
2942 * whether it wants to wake up a task to maintain
2943 * concurrency.
2944 */
2945 if (prev->flags & PF_WQ_WORKER) {
2946 struct task_struct *to_wakeup;
2947
2948 to_wakeup = wq_worker_sleeping(prev, cpu);
2949 if (to_wakeup)
2950 try_to_wake_up_local(to_wakeup);
2951 }
2952 }
2953 switch_count = &prev->nvcsw;
2954 }
2955
2956 pre_schedule(rq, prev);
2957
2958 if (unlikely(!rq->nr_running))
2959 idle_balance(cpu, rq);
2960
2961 put_prev_task(rq, prev);
2962 next = pick_next_task(rq);
2963 clear_tsk_need_resched(prev);
2964 rq->skip_clock_update = 0;
2965
2966 if (likely(prev != next)) {
2967 rq->nr_switches++;
2968 rq->curr = next;
2969 ++*switch_count;
2970
2971 context_switch(rq, prev, next); /* unlocks the rq */
2972 /*
2973 * The context switch have flipped the stack from under us
2974 * and restored the local variables which were saved when
2975 * this task called schedule() in the past. prev == current
2976 * is still correct, but it can be moved to another cpu/rq.
2977 */
2978 cpu = smp_processor_id();
2979 rq = cpu_rq(cpu);
2980 } else
2981 raw_spin_unlock_irq(&rq->lock);
2982
2983 post_schedule(rq);
2984
2985 sched_preempt_enable_no_resched();
2986 if (need_resched())
2987 goto need_resched;
2988 }
2989
2990 static inline void sched_submit_work(struct task_struct *tsk)
2991 {
2992 if (!tsk->state || tsk_is_pi_blocked(tsk))
2993 return;
2994 /*
2995 * If we are going to sleep and we have plugged IO queued,
2996 * make sure to submit it to avoid deadlocks.
2997 */
2998 if (blk_needs_flush_plug(tsk))
2999 blk_schedule_flush_plug(tsk);
3000 }
3001
3002 asmlinkage void __sched schedule(void)
3003 {
3004 struct task_struct *tsk = current;
3005
3006 sched_submit_work(tsk);
3007 __schedule();
3008 }
3009 EXPORT_SYMBOL(schedule);
3010
3011 #ifdef CONFIG_CONTEXT_TRACKING
3012 asmlinkage void __sched schedule_user(void)
3013 {
3014 /*
3015 * If we come here after a random call to set_need_resched(),
3016 * or we have been woken up remotely but the IPI has not yet arrived,
3017 * we haven't yet exited the RCU idle mode. Do it here manually until
3018 * we find a better solution.
3019 */
3020 user_exit();
3021 schedule();
3022 user_enter();
3023 }
3024 #endif
3025
3026 /**
3027 * schedule_preempt_disabled - called with preemption disabled
3028 *
3029 * Returns with preemption disabled. Note: preempt_count must be 1
3030 */
3031 void __sched schedule_preempt_disabled(void)
3032 {
3033 sched_preempt_enable_no_resched();
3034 schedule();
3035 preempt_disable();
3036 }
3037
3038 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
3039
3040 static inline bool owner_running(struct mutex *lock, struct task_struct *owner)
3041 {
3042 if (lock->owner != owner)
3043 return false;
3044
3045 /*
3046 * Ensure we emit the owner->on_cpu, dereference _after_ checking
3047 * lock->owner still matches owner, if that fails, owner might
3048 * point to free()d memory, if it still matches, the rcu_read_lock()
3049 * ensures the memory stays valid.
3050 */
3051 barrier();
3052
3053 return owner->on_cpu;
3054 }
3055
3056 /*
3057 * Look out! "owner" is an entirely speculative pointer
3058 * access and not reliable.
3059 */
3060 int mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner)
3061 {
3062 if (!sched_feat(OWNER_SPIN))
3063 return 0;
3064
3065 rcu_read_lock();
3066 while (owner_running(lock, owner)) {
3067 if (need_resched())
3068 break;
3069
3070 arch_mutex_cpu_relax();
3071 }
3072 rcu_read_unlock();
3073
3074 /*
3075 * We break out the loop above on need_resched() and when the
3076 * owner changed, which is a sign for heavy contention. Return
3077 * success only when lock->owner is NULL.
3078 */
3079 return lock->owner == NULL;
3080 }
3081 #endif
3082
3083 #ifdef CONFIG_PREEMPT
3084 /*
3085 * this is the entry point to schedule() from in-kernel preemption
3086 * off of preempt_enable. Kernel preemptions off return from interrupt
3087 * occur there and call schedule directly.
3088 */
3089 asmlinkage void __sched notrace preempt_schedule(void)
3090 {
3091 struct thread_info *ti = current_thread_info();
3092
3093 /*
3094 * If there is a non-zero preempt_count or interrupts are disabled,
3095 * we do not want to preempt the current task. Just return..
3096 */
3097 if (likely(ti->preempt_count || irqs_disabled()))
3098 return;
3099
3100 do {
3101 add_preempt_count_notrace(PREEMPT_ACTIVE);
3102 __schedule();
3103 sub_preempt_count_notrace(PREEMPT_ACTIVE);
3104
3105 /*
3106 * Check again in case we missed a preemption opportunity
3107 * between schedule and now.
3108 */
3109 barrier();
3110 } while (need_resched());
3111 }
3112 EXPORT_SYMBOL(preempt_schedule);
3113
3114 /*
3115 * this is the entry point to schedule() from kernel preemption
3116 * off of irq context.
3117 * Note, that this is called and return with irqs disabled. This will
3118 * protect us against recursive calling from irq.
3119 */
3120 asmlinkage void __sched preempt_schedule_irq(void)
3121 {
3122 struct thread_info *ti = current_thread_info();
3123 enum ctx_state prev_state;
3124
3125 /* Catch callers which need to be fixed */
3126 BUG_ON(ti->preempt_count || !irqs_disabled());
3127
3128 prev_state = exception_enter();
3129
3130 do {
3131 add_preempt_count(PREEMPT_ACTIVE);
3132 local_irq_enable();
3133 __schedule();
3134 local_irq_disable();
3135 sub_preempt_count(PREEMPT_ACTIVE);
3136
3137 /*
3138 * Check again in case we missed a preemption opportunity
3139 * between schedule and now.
3140 */
3141 barrier();
3142 } while (need_resched());
3143
3144 exception_exit(prev_state);
3145 }
3146
3147 #endif /* CONFIG_PREEMPT */
3148
3149 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3150 void *key)
3151 {
3152 return try_to_wake_up(curr->private, mode, wake_flags);
3153 }
3154 EXPORT_SYMBOL(default_wake_function);
3155
3156 /*
3157 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3158 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3159 * number) then we wake all the non-exclusive tasks and one exclusive task.
3160 *
3161 * There are circumstances in which we can try to wake a task which has already
3162 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3163 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3164 */
3165 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3166 int nr_exclusive, int wake_flags, void *key)
3167 {
3168 wait_queue_t *curr, *next;
3169
3170 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3171 unsigned flags = curr->flags;
3172
3173 if (curr->func(curr, mode, wake_flags, key) &&
3174 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3175 break;
3176 }
3177 }
3178
3179 /**
3180 * __wake_up - wake up threads blocked on a waitqueue.
3181 * @q: the waitqueue
3182 * @mode: which threads
3183 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3184 * @key: is directly passed to the wakeup function
3185 *
3186 * It may be assumed that this function implies a write memory barrier before
3187 * changing the task state if and only if any tasks are woken up.
3188 */
3189 void __wake_up(wait_queue_head_t *q, unsigned int mode,
3190 int nr_exclusive, void *key)
3191 {
3192 unsigned long flags;
3193
3194 spin_lock_irqsave(&q->lock, flags);
3195 __wake_up_common(q, mode, nr_exclusive, 0, key);
3196 spin_unlock_irqrestore(&q->lock, flags);
3197 }
3198 EXPORT_SYMBOL(__wake_up);
3199
3200 /*
3201 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3202 */
3203 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr)
3204 {
3205 __wake_up_common(q, mode, nr, 0, NULL);
3206 }
3207 EXPORT_SYMBOL_GPL(__wake_up_locked);
3208
3209 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
3210 {
3211 __wake_up_common(q, mode, 1, 0, key);
3212 }
3213 EXPORT_SYMBOL_GPL(__wake_up_locked_key);
3214
3215 /**
3216 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
3217 * @q: the waitqueue
3218 * @mode: which threads
3219 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3220 * @key: opaque value to be passed to wakeup targets
3221 *
3222 * The sync wakeup differs that the waker knows that it will schedule
3223 * away soon, so while the target thread will be woken up, it will not
3224 * be migrated to another CPU - ie. the two threads are 'synchronized'
3225 * with each other. This can prevent needless bouncing between CPUs.
3226 *
3227 * On UP it can prevent extra preemption.
3228 *
3229 * It may be assumed that this function implies a write memory barrier before
3230 * changing the task state if and only if any tasks are woken up.
3231 */
3232 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
3233 int nr_exclusive, void *key)
3234 {
3235 unsigned long flags;
3236 int wake_flags = WF_SYNC;
3237
3238 if (unlikely(!q))
3239 return;
3240
3241 if (unlikely(!nr_exclusive))
3242 wake_flags = 0;
3243
3244 spin_lock_irqsave(&q->lock, flags);
3245 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
3246 spin_unlock_irqrestore(&q->lock, flags);
3247 }
3248 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
3249
3250 /*
3251 * __wake_up_sync - see __wake_up_sync_key()
3252 */
3253 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3254 {
3255 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
3256 }
3257 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3258
3259 /**
3260 * complete: - signals a single thread waiting on this completion
3261 * @x: holds the state of this particular completion
3262 *
3263 * This will wake up a single thread waiting on this completion. Threads will be
3264 * awakened in the same order in which they were queued.
3265 *
3266 * See also complete_all(), wait_for_completion() and related routines.
3267 *
3268 * It may be assumed that this function implies a write memory barrier before
3269 * changing the task state if and only if any tasks are woken up.
3270 */
3271 void complete(struct completion *x)
3272 {
3273 unsigned long flags;
3274
3275 spin_lock_irqsave(&x->wait.lock, flags);
3276 x->done++;
3277 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
3278 spin_unlock_irqrestore(&x->wait.lock, flags);
3279 }
3280 EXPORT_SYMBOL(complete);
3281
3282 /**
3283 * complete_all: - signals all threads waiting on this completion
3284 * @x: holds the state of this particular completion
3285 *
3286 * This will wake up all threads waiting on this particular completion event.
3287 *
3288 * It may be assumed that this function implies a write memory barrier before
3289 * changing the task state if and only if any tasks are woken up.
3290 */
3291 void complete_all(struct completion *x)
3292 {
3293 unsigned long flags;
3294
3295 spin_lock_irqsave(&x->wait.lock, flags);
3296 x->done += UINT_MAX/2;
3297 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
3298 spin_unlock_irqrestore(&x->wait.lock, flags);
3299 }
3300 EXPORT_SYMBOL(complete_all);
3301
3302 static inline long __sched
3303 do_wait_for_common(struct completion *x,
3304 long (*action)(long), long timeout, int state)
3305 {
3306 if (!x->done) {
3307 DECLARE_WAITQUEUE(wait, current);
3308
3309 __add_wait_queue_tail_exclusive(&x->wait, &wait);
3310 do {
3311 if (signal_pending_state(state, current)) {
3312 timeout = -ERESTARTSYS;
3313 break;
3314 }
3315 __set_current_state(state);
3316 spin_unlock_irq(&x->wait.lock);
3317 timeout = action(timeout);
3318 spin_lock_irq(&x->wait.lock);
3319 } while (!x->done && timeout);
3320 __remove_wait_queue(&x->wait, &wait);
3321 if (!x->done)
3322 return timeout;
3323 }
3324 x->done--;
3325 return timeout ?: 1;
3326 }
3327
3328 static inline long __sched
3329 __wait_for_common(struct completion *x,
3330 long (*action)(long), long timeout, int state)
3331 {
3332 might_sleep();
3333
3334 spin_lock_irq(&x->wait.lock);
3335 timeout = do_wait_for_common(x, action, timeout, state);
3336 spin_unlock_irq(&x->wait.lock);
3337 return timeout;
3338 }
3339
3340 static long __sched
3341 wait_for_common(struct completion *x, long timeout, int state)
3342 {
3343 return __wait_for_common(x, schedule_timeout, timeout, state);
3344 }
3345
3346 static long __sched
3347 wait_for_common_io(struct completion *x, long timeout, int state)
3348 {
3349 return __wait_for_common(x, io_schedule_timeout, timeout, state);
3350 }
3351
3352 /**
3353 * wait_for_completion: - waits for completion of a task
3354 * @x: holds the state of this particular completion
3355 *
3356 * This waits to be signaled for completion of a specific task. It is NOT
3357 * interruptible and there is no timeout.
3358 *
3359 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
3360 * and interrupt capability. Also see complete().
3361 */
3362 void __sched wait_for_completion(struct completion *x)
3363 {
3364 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
3365 }
3366 EXPORT_SYMBOL(wait_for_completion);
3367
3368 /**
3369 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
3370 * @x: holds the state of this particular completion
3371 * @timeout: timeout value in jiffies
3372 *
3373 * This waits for either a completion of a specific task to be signaled or for a
3374 * specified timeout to expire. The timeout is in jiffies. It is not
3375 * interruptible.
3376 *
3377 * The return value is 0 if timed out, and positive (at least 1, or number of
3378 * jiffies left till timeout) if completed.
3379 */
3380 unsigned long __sched
3381 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3382 {
3383 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
3384 }
3385 EXPORT_SYMBOL(wait_for_completion_timeout);
3386
3387 /**
3388 * wait_for_completion_io: - waits for completion of a task
3389 * @x: holds the state of this particular completion
3390 *
3391 * This waits to be signaled for completion of a specific task. It is NOT
3392 * interruptible and there is no timeout. The caller is accounted as waiting
3393 * for IO.
3394 */
3395 void __sched wait_for_completion_io(struct completion *x)
3396 {
3397 wait_for_common_io(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
3398 }
3399 EXPORT_SYMBOL(wait_for_completion_io);
3400
3401 /**
3402 * wait_for_completion_io_timeout: - waits for completion of a task (w/timeout)
3403 * @x: holds the state of this particular completion
3404 * @timeout: timeout value in jiffies
3405 *
3406 * This waits for either a completion of a specific task to be signaled or for a
3407 * specified timeout to expire. The timeout is in jiffies. It is not
3408 * interruptible. The caller is accounted as waiting for IO.
3409 *
3410 * The return value is 0 if timed out, and positive (at least 1, or number of
3411 * jiffies left till timeout) if completed.
3412 */
3413 unsigned long __sched
3414 wait_for_completion_io_timeout(struct completion *x, unsigned long timeout)
3415 {
3416 return wait_for_common_io(x, timeout, TASK_UNINTERRUPTIBLE);
3417 }
3418 EXPORT_SYMBOL(wait_for_completion_io_timeout);
3419
3420 /**
3421 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
3422 * @x: holds the state of this particular completion
3423 *
3424 * This waits for completion of a specific task to be signaled. It is
3425 * interruptible.
3426 *
3427 * The return value is -ERESTARTSYS if interrupted, 0 if completed.
3428 */
3429 int __sched wait_for_completion_interruptible(struct completion *x)
3430 {
3431 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
3432 if (t == -ERESTARTSYS)
3433 return t;
3434 return 0;
3435 }
3436 EXPORT_SYMBOL(wait_for_completion_interruptible);
3437
3438 /**
3439 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
3440 * @x: holds the state of this particular completion
3441 * @timeout: timeout value in jiffies
3442 *
3443 * This waits for either a completion of a specific task to be signaled or for a
3444 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
3445 *
3446 * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3447 * positive (at least 1, or number of jiffies left till timeout) if completed.
3448 */
3449 long __sched
3450 wait_for_completion_interruptible_timeout(struct completion *x,
3451 unsigned long timeout)
3452 {
3453 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
3454 }
3455 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3456
3457 /**
3458 * wait_for_completion_killable: - waits for completion of a task (killable)
3459 * @x: holds the state of this particular completion
3460 *
3461 * This waits to be signaled for completion of a specific task. It can be
3462 * interrupted by a kill signal.
3463 *
3464 * The return value is -ERESTARTSYS if interrupted, 0 if completed.
3465 */
3466 int __sched wait_for_completion_killable(struct completion *x)
3467 {
3468 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
3469 if (t == -ERESTARTSYS)
3470 return t;
3471 return 0;
3472 }
3473 EXPORT_SYMBOL(wait_for_completion_killable);
3474
3475 /**
3476 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
3477 * @x: holds the state of this particular completion
3478 * @timeout: timeout value in jiffies
3479 *
3480 * This waits for either a completion of a specific task to be
3481 * signaled or for a specified timeout to expire. It can be
3482 * interrupted by a kill signal. The timeout is in jiffies.
3483 *
3484 * The return value is -ERESTARTSYS if interrupted, 0 if timed out,
3485 * positive (at least 1, or number of jiffies left till timeout) if completed.
3486 */
3487 long __sched
3488 wait_for_completion_killable_timeout(struct completion *x,
3489 unsigned long timeout)
3490 {
3491 return wait_for_common(x, timeout, TASK_KILLABLE);
3492 }
3493 EXPORT_SYMBOL(wait_for_completion_killable_timeout);
3494
3495 /**
3496 * try_wait_for_completion - try to decrement a completion without blocking
3497 * @x: completion structure
3498 *
3499 * Returns: 0 if a decrement cannot be done without blocking
3500 * 1 if a decrement succeeded.
3501 *
3502 * If a completion is being used as a counting completion,
3503 * attempt to decrement the counter without blocking. This
3504 * enables us to avoid waiting if the resource the completion
3505 * is protecting is not available.
3506 */
3507 bool try_wait_for_completion(struct completion *x)
3508 {
3509 unsigned long flags;
3510 int ret = 1;
3511
3512 spin_lock_irqsave(&x->wait.lock, flags);
3513 if (!x->done)
3514 ret = 0;
3515 else
3516 x->done--;
3517 spin_unlock_irqrestore(&x->wait.lock, flags);
3518 return ret;
3519 }
3520 EXPORT_SYMBOL(try_wait_for_completion);
3521
3522 /**
3523 * completion_done - Test to see if a completion has any waiters
3524 * @x: completion structure
3525 *
3526 * Returns: 0 if there are waiters (wait_for_completion() in progress)
3527 * 1 if there are no waiters.
3528 *
3529 */
3530 bool completion_done(struct completion *x)
3531 {
3532 unsigned long flags;
3533 int ret = 1;
3534
3535 spin_lock_irqsave(&x->wait.lock, flags);
3536 if (!x->done)
3537 ret = 0;
3538 spin_unlock_irqrestore(&x->wait.lock, flags);
3539 return ret;
3540 }
3541 EXPORT_SYMBOL(completion_done);
3542
3543 static long __sched
3544 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
3545 {
3546 unsigned long flags;
3547 wait_queue_t wait;
3548
3549 init_waitqueue_entry(&wait, current);
3550
3551 __set_current_state(state);
3552
3553 spin_lock_irqsave(&q->lock, flags);
3554 __add_wait_queue(q, &wait);
3555 spin_unlock(&q->lock);
3556 timeout = schedule_timeout(timeout);
3557 spin_lock_irq(&q->lock);
3558 __remove_wait_queue(q, &wait);
3559 spin_unlock_irqrestore(&q->lock, flags);
3560
3561 return timeout;
3562 }
3563
3564 void __sched interruptible_sleep_on(wait_queue_head_t *q)
3565 {
3566 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
3567 }
3568 EXPORT_SYMBOL(interruptible_sleep_on);
3569
3570 long __sched
3571 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3572 {
3573 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
3574 }
3575 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3576
3577 void __sched sleep_on(wait_queue_head_t *q)
3578 {
3579 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
3580 }
3581 EXPORT_SYMBOL(sleep_on);
3582
3583 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3584 {
3585 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
3586 }
3587 EXPORT_SYMBOL(sleep_on_timeout);
3588
3589 #ifdef CONFIG_RT_MUTEXES
3590
3591 /*
3592 * rt_mutex_setprio - set the current priority of a task
3593 * @p: task
3594 * @prio: prio value (kernel-internal form)
3595 *
3596 * This function changes the 'effective' priority of a task. It does
3597 * not touch ->normal_prio like __setscheduler().
3598 *
3599 * Used by the rt_mutex code to implement priority inheritance logic.
3600 */
3601 void rt_mutex_setprio(struct task_struct *p, int prio)
3602 {
3603 int oldprio, on_rq, running;
3604 struct rq *rq;
3605 const struct sched_class *prev_class;
3606
3607 BUG_ON(prio < 0 || prio > MAX_PRIO);
3608
3609 rq = __task_rq_lock(p);
3610
3611 /*
3612 * Idle task boosting is a nono in general. There is one
3613 * exception, when PREEMPT_RT and NOHZ is active:
3614 *
3615 * The idle task calls get_next_timer_interrupt() and holds
3616 * the timer wheel base->lock on the CPU and another CPU wants
3617 * to access the timer (probably to cancel it). We can safely
3618 * ignore the boosting request, as the idle CPU runs this code
3619 * with interrupts disabled and will complete the lock
3620 * protected section without being interrupted. So there is no
3621 * real need to boost.
3622 */
3623 if (unlikely(p == rq->idle)) {
3624 WARN_ON(p != rq->curr);
3625 WARN_ON(p->pi_blocked_on);
3626 goto out_unlock;
3627 }
3628
3629 trace_sched_pi_setprio(p, prio);
3630 oldprio = p->prio;
3631 prev_class = p->sched_class;
3632 on_rq = p->on_rq;
3633 running = task_current(rq, p);
3634 if (on_rq)
3635 dequeue_task(rq, p, 0);
3636 if (running)
3637 p->sched_class->put_prev_task(rq, p);
3638
3639 if (rt_prio(prio))
3640 p->sched_class = &rt_sched_class;
3641 else
3642 p->sched_class = &fair_sched_class;
3643
3644 p->prio = prio;
3645
3646 if (running)
3647 p->sched_class->set_curr_task(rq);
3648 if (on_rq)
3649 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
3650
3651 check_class_changed(rq, p, prev_class, oldprio);
3652 out_unlock:
3653 __task_rq_unlock(rq);
3654 }
3655 #endif
3656 void set_user_nice(struct task_struct *p, long nice)
3657 {
3658 int old_prio, delta, on_rq;
3659 unsigned long flags;
3660 struct rq *rq;
3661
3662 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3663 return;
3664 /*
3665 * We have to be careful, if called from sys_setpriority(),
3666 * the task might be in the middle of scheduling on another CPU.
3667 */
3668 rq = task_rq_lock(p, &flags);
3669 /*
3670 * The RT priorities are set via sched_setscheduler(), but we still
3671 * allow the 'normal' nice value to be set - but as expected
3672 * it wont have any effect on scheduling until the task is
3673 * SCHED_FIFO/SCHED_RR:
3674 */
3675 if (task_has_rt_policy(p)) {
3676 p->static_prio = NICE_TO_PRIO(nice);
3677 goto out_unlock;
3678 }
3679 on_rq = p->on_rq;
3680 if (on_rq)
3681 dequeue_task(rq, p, 0);
3682
3683 p->static_prio = NICE_TO_PRIO(nice);
3684 set_load_weight(p);
3685 old_prio = p->prio;
3686 p->prio = effective_prio(p);
3687 delta = p->prio - old_prio;
3688
3689 if (on_rq) {
3690 enqueue_task(rq, p, 0);
3691 /*
3692 * If the task increased its priority or is running and
3693 * lowered its priority, then reschedule its CPU:
3694 */
3695 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3696 resched_task(rq->curr);
3697 }
3698 out_unlock:
3699 task_rq_unlock(rq, p, &flags);
3700 }
3701 EXPORT_SYMBOL(set_user_nice);
3702
3703 /*
3704 * can_nice - check if a task can reduce its nice value
3705 * @p: task
3706 * @nice: nice value
3707 */
3708 int can_nice(const struct task_struct *p, const int nice)
3709 {
3710 /* convert nice value [19,-20] to rlimit style value [1,40] */
3711 int nice_rlim = 20 - nice;
3712
3713 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3714 capable(CAP_SYS_NICE));
3715 }
3716
3717 #ifdef __ARCH_WANT_SYS_NICE
3718
3719 /*
3720 * sys_nice - change the priority of the current process.
3721 * @increment: priority increment
3722 *
3723 * sys_setpriority is a more generic, but much slower function that
3724 * does similar things.
3725 */
3726 SYSCALL_DEFINE1(nice, int, increment)
3727 {
3728 long nice, retval;
3729
3730 /*
3731 * Setpriority might change our priority at the same moment.
3732 * We don't have to worry. Conceptually one call occurs first
3733 * and we have a single winner.
3734 */
3735 if (increment < -40)
3736 increment = -40;
3737 if (increment > 40)
3738 increment = 40;
3739
3740 nice = TASK_NICE(current) + increment;
3741 if (nice < -20)
3742 nice = -20;
3743 if (nice > 19)
3744 nice = 19;
3745
3746 if (increment < 0 && !can_nice(current, nice))
3747 return -EPERM;
3748
3749 retval = security_task_setnice(current, nice);
3750 if (retval)
3751 return retval;
3752
3753 set_user_nice(current, nice);
3754 return 0;
3755 }
3756
3757 #endif
3758
3759 /**
3760 * task_prio - return the priority value of a given task.
3761 * @p: the task in question.
3762 *
3763 * This is the priority value as seen by users in /proc.
3764 * RT tasks are offset by -200. Normal tasks are centered
3765 * around 0, value goes from -16 to +15.
3766 */
3767 int task_prio(const struct task_struct *p)
3768 {
3769 return p->prio - MAX_RT_PRIO;
3770 }
3771
3772 /**
3773 * task_nice - return the nice value of a given task.
3774 * @p: the task in question.
3775 */
3776 int task_nice(const struct task_struct *p)
3777 {
3778 return TASK_NICE(p);
3779 }
3780 EXPORT_SYMBOL(task_nice);
3781
3782 /**
3783 * idle_cpu - is a given cpu idle currently?
3784 * @cpu: the processor in question.
3785 */
3786 int idle_cpu(int cpu)
3787 {
3788 struct rq *rq = cpu_rq(cpu);
3789
3790 if (rq->curr != rq->idle)
3791 return 0;
3792
3793 if (rq->nr_running)
3794 return 0;
3795
3796 #ifdef CONFIG_SMP
3797 if (!llist_empty(&rq->wake_list))
3798 return 0;
3799 #endif
3800
3801 return 1;
3802 }
3803
3804 /**
3805 * idle_task - return the idle task for a given cpu.
3806 * @cpu: the processor in question.
3807 */
3808 struct task_struct *idle_task(int cpu)
3809 {
3810 return cpu_rq(cpu)->idle;
3811 }
3812
3813 /**
3814 * find_process_by_pid - find a process with a matching PID value.
3815 * @pid: the pid in question.
3816 */
3817 static struct task_struct *find_process_by_pid(pid_t pid)
3818 {
3819 return pid ? find_task_by_vpid(pid) : current;
3820 }
3821
3822 /* Actually do priority change: must hold rq lock. */
3823 static void
3824 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
3825 {
3826 p->policy = policy;
3827 p->rt_priority = prio;
3828 p->normal_prio = normal_prio(p);
3829 /* we are holding p->pi_lock already */
3830 p->prio = rt_mutex_getprio(p);
3831 if (rt_prio(p->prio))
3832 p->sched_class = &rt_sched_class;
3833 else
3834 p->sched_class = &fair_sched_class;
3835 set_load_weight(p);
3836 }
3837
3838 /*
3839 * check the target process has a UID that matches the current process's
3840 */
3841 static bool check_same_owner(struct task_struct *p)
3842 {
3843 const struct cred *cred = current_cred(), *pcred;
3844 bool match;
3845
3846 rcu_read_lock();
3847 pcred = __task_cred(p);
3848 match = (uid_eq(cred->euid, pcred->euid) ||
3849 uid_eq(cred->euid, pcred->uid));
3850 rcu_read_unlock();
3851 return match;
3852 }
3853
3854 static int __sched_setscheduler(struct task_struct *p, int policy,
3855 const struct sched_param *param, bool user)
3856 {
3857 int retval, oldprio, oldpolicy = -1, on_rq, running;
3858 unsigned long flags;
3859 const struct sched_class *prev_class;
3860 struct rq *rq;
3861 int reset_on_fork;
3862
3863 /* may grab non-irq protected spin_locks */
3864 BUG_ON(in_interrupt());
3865 recheck:
3866 /* double check policy once rq lock held */
3867 if (policy < 0) {
3868 reset_on_fork = p->sched_reset_on_fork;
3869 policy = oldpolicy = p->policy;
3870 } else {
3871 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
3872 policy &= ~SCHED_RESET_ON_FORK;
3873
3874 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3875 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
3876 policy != SCHED_IDLE)
3877 return -EINVAL;
3878 }
3879
3880 /*
3881 * Valid priorities for SCHED_FIFO and SCHED_RR are
3882 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
3883 * SCHED_BATCH and SCHED_IDLE is 0.
3884 */
3885 if (param->sched_priority < 0 ||
3886 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
3887 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
3888 return -EINVAL;
3889 if (rt_policy(policy) != (param->sched_priority != 0))
3890 return -EINVAL;
3891
3892 /*
3893 * Allow unprivileged RT tasks to decrease priority:
3894 */
3895 if (user && !capable(CAP_SYS_NICE)) {
3896 if (rt_policy(policy)) {
3897 unsigned long rlim_rtprio =
3898 task_rlimit(p, RLIMIT_RTPRIO);
3899
3900 /* can't set/change the rt policy */
3901 if (policy != p->policy && !rlim_rtprio)
3902 return -EPERM;
3903
3904 /* can't increase priority */
3905 if (param->sched_priority > p->rt_priority &&
3906 param->sched_priority > rlim_rtprio)
3907 return -EPERM;
3908 }
3909
3910 /*
3911 * Treat SCHED_IDLE as nice 20. Only allow a switch to
3912 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
3913 */
3914 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
3915 if (!can_nice(p, TASK_NICE(p)))
3916 return -EPERM;
3917 }
3918
3919 /* can't change other user's priorities */
3920 if (!check_same_owner(p))
3921 return -EPERM;
3922
3923 /* Normal users shall not reset the sched_reset_on_fork flag */
3924 if (p->sched_reset_on_fork && !reset_on_fork)
3925 return -EPERM;
3926 }
3927
3928 if (user) {
3929 retval = security_task_setscheduler(p);
3930 if (retval)
3931 return retval;
3932 }
3933
3934 /*
3935 * make sure no PI-waiters arrive (or leave) while we are
3936 * changing the priority of the task:
3937 *
3938 * To be able to change p->policy safely, the appropriate
3939 * runqueue lock must be held.
3940 */
3941 rq = task_rq_lock(p, &flags);
3942
3943 /*
3944 * Changing the policy of the stop threads its a very bad idea
3945 */
3946 if (p == rq->stop) {
3947 task_rq_unlock(rq, p, &flags);
3948 return -EINVAL;
3949 }
3950
3951 /*
3952 * If not changing anything there's no need to proceed further:
3953 */
3954 if (unlikely(policy == p->policy && (!rt_policy(policy) ||
3955 param->sched_priority == p->rt_priority))) {
3956 task_rq_unlock(rq, p, &flags);
3957 return 0;
3958 }
3959
3960 #ifdef CONFIG_RT_GROUP_SCHED
3961 if (user) {
3962 /*
3963 * Do not allow realtime tasks into groups that have no runtime
3964 * assigned.
3965 */
3966 if (rt_bandwidth_enabled() && rt_policy(policy) &&
3967 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
3968 !task_group_is_autogroup(task_group(p))) {
3969 task_rq_unlock(rq, p, &flags);
3970 return -EPERM;
3971 }
3972 }
3973 #endif
3974
3975 /* recheck policy now with rq lock held */
3976 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3977 policy = oldpolicy = -1;
3978 task_rq_unlock(rq, p, &flags);
3979 goto recheck;
3980 }
3981 on_rq = p->on_rq;
3982 running = task_current(rq, p);
3983 if (on_rq)
3984 dequeue_task(rq, p, 0);
3985 if (running)
3986 p->sched_class->put_prev_task(rq, p);
3987
3988 p->sched_reset_on_fork = reset_on_fork;
3989
3990 oldprio = p->prio;
3991 prev_class = p->sched_class;
3992 __setscheduler(rq, p, policy, param->sched_priority);
3993
3994 if (running)
3995 p->sched_class->set_curr_task(rq);
3996 if (on_rq)
3997 enqueue_task(rq, p, 0);
3998
3999 check_class_changed(rq, p, prev_class, oldprio);
4000 task_rq_unlock(rq, p, &flags);
4001
4002 rt_mutex_adjust_pi(p);
4003
4004 return 0;
4005 }
4006
4007 /**
4008 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4009 * @p: the task in question.
4010 * @policy: new policy.
4011 * @param: structure containing the new RT priority.
4012 *
4013 * NOTE that the task may be already dead.
4014 */
4015 int sched_setscheduler(struct task_struct *p, int policy,
4016 const struct sched_param *param)
4017 {
4018 return __sched_setscheduler(p, policy, param, true);
4019 }
4020 EXPORT_SYMBOL_GPL(sched_setscheduler);
4021
4022 /**
4023 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4024 * @p: the task in question.
4025 * @policy: new policy.
4026 * @param: structure containing the new RT priority.
4027 *
4028 * Just like sched_setscheduler, only don't bother checking if the
4029 * current context has permission. For example, this is needed in
4030 * stop_machine(): we create temporary high priority worker threads,
4031 * but our caller might not have that capability.
4032 */
4033 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4034 const struct sched_param *param)
4035 {
4036 return __sched_setscheduler(p, policy, param, false);
4037 }
4038
4039 static int
4040 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4041 {
4042 struct sched_param lparam;
4043 struct task_struct *p;
4044 int retval;
4045
4046 if (!param || pid < 0)
4047 return -EINVAL;
4048 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4049 return -EFAULT;
4050
4051 rcu_read_lock();
4052 retval = -ESRCH;
4053 p = find_process_by_pid(pid);
4054 if (p != NULL)
4055 retval = sched_setscheduler(p, policy, &lparam);
4056 rcu_read_unlock();
4057
4058 return retval;
4059 }
4060
4061 /**
4062 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4063 * @pid: the pid in question.
4064 * @policy: new policy.
4065 * @param: structure containing the new RT priority.
4066 */
4067 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4068 struct sched_param __user *, param)
4069 {
4070 /* negative values for policy are not valid */
4071 if (policy < 0)
4072 return -EINVAL;
4073
4074 return do_sched_setscheduler(pid, policy, param);
4075 }
4076
4077 /**
4078 * sys_sched_setparam - set/change the RT priority of a thread
4079 * @pid: the pid in question.
4080 * @param: structure containing the new RT priority.
4081 */
4082 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4083 {
4084 return do_sched_setscheduler(pid, -1, param);
4085 }
4086
4087 /**
4088 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4089 * @pid: the pid in question.
4090 */
4091 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4092 {
4093 struct task_struct *p;
4094 int retval;
4095
4096 if (pid < 0)
4097 return -EINVAL;
4098
4099 retval = -ESRCH;
4100 rcu_read_lock();
4101 p = find_process_by_pid(pid);
4102 if (p) {
4103 retval = security_task_getscheduler(p);
4104 if (!retval)
4105 retval = p->policy
4106 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4107 }
4108 rcu_read_unlock();
4109 return retval;
4110 }
4111
4112 /**
4113 * sys_sched_getparam - get the RT priority of a thread
4114 * @pid: the pid in question.
4115 * @param: structure containing the RT priority.
4116 */
4117 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4118 {
4119 struct sched_param lp;
4120 struct task_struct *p;
4121 int retval;
4122
4123 if (!param || pid < 0)
4124 return -EINVAL;
4125
4126 rcu_read_lock();
4127 p = find_process_by_pid(pid);
4128 retval = -ESRCH;
4129 if (!p)
4130 goto out_unlock;
4131
4132 retval = security_task_getscheduler(p);
4133 if (retval)
4134 goto out_unlock;
4135
4136 lp.sched_priority = p->rt_priority;
4137 rcu_read_unlock();
4138
4139 /*
4140 * This one might sleep, we cannot do it with a spinlock held ...
4141 */
4142 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4143
4144 return retval;
4145
4146 out_unlock:
4147 rcu_read_unlock();
4148 return retval;
4149 }
4150
4151 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4152 {
4153 cpumask_var_t cpus_allowed, new_mask;
4154 struct task_struct *p;
4155 int retval;
4156
4157 get_online_cpus();
4158 rcu_read_lock();
4159
4160 p = find_process_by_pid(pid);
4161 if (!p) {
4162 rcu_read_unlock();
4163 put_online_cpus();
4164 return -ESRCH;
4165 }
4166
4167 /* Prevent p going away */
4168 get_task_struct(p);
4169 rcu_read_unlock();
4170
4171 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4172 retval = -ENOMEM;
4173 goto out_put_task;
4174 }
4175 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4176 retval = -ENOMEM;
4177 goto out_free_cpus_allowed;
4178 }
4179 retval = -EPERM;
4180 if (!check_same_owner(p)) {
4181 rcu_read_lock();
4182 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4183 rcu_read_unlock();
4184 goto out_unlock;
4185 }
4186 rcu_read_unlock();
4187 }
4188
4189 retval = security_task_setscheduler(p);
4190 if (retval)
4191 goto out_unlock;
4192
4193 cpuset_cpus_allowed(p, cpus_allowed);
4194 cpumask_and(new_mask, in_mask, cpus_allowed);
4195 again:
4196 retval = set_cpus_allowed_ptr(p, new_mask);
4197
4198 if (!retval) {
4199 cpuset_cpus_allowed(p, cpus_allowed);
4200 if (!cpumask_subset(new_mask, cpus_allowed)) {
4201 /*
4202 * We must have raced with a concurrent cpuset
4203 * update. Just reset the cpus_allowed to the
4204 * cpuset's cpus_allowed
4205 */
4206 cpumask_copy(new_mask, cpus_allowed);
4207 goto again;
4208 }
4209 }
4210 out_unlock:
4211 free_cpumask_var(new_mask);
4212 out_free_cpus_allowed:
4213 free_cpumask_var(cpus_allowed);
4214 out_put_task:
4215 put_task_struct(p);
4216 put_online_cpus();
4217 return retval;
4218 }
4219
4220 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4221 struct cpumask *new_mask)
4222 {
4223 if (len < cpumask_size())
4224 cpumask_clear(new_mask);
4225 else if (len > cpumask_size())
4226 len = cpumask_size();
4227
4228 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4229 }
4230
4231 /**
4232 * sys_sched_setaffinity - set the cpu affinity of a process
4233 * @pid: pid of the process
4234 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4235 * @user_mask_ptr: user-space pointer to the new cpu mask
4236 */
4237 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4238 unsigned long __user *, user_mask_ptr)
4239 {
4240 cpumask_var_t new_mask;
4241 int retval;
4242
4243 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4244 return -ENOMEM;
4245
4246 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4247 if (retval == 0)
4248 retval = sched_setaffinity(pid, new_mask);
4249 free_cpumask_var(new_mask);
4250 return retval;
4251 }
4252
4253 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4254 {
4255 struct task_struct *p;
4256 unsigned long flags;
4257 int retval;
4258
4259 get_online_cpus();
4260 rcu_read_lock();
4261
4262 retval = -ESRCH;
4263 p = find_process_by_pid(pid);
4264 if (!p)
4265 goto out_unlock;
4266
4267 retval = security_task_getscheduler(p);
4268 if (retval)
4269 goto out_unlock;
4270
4271 raw_spin_lock_irqsave(&p->pi_lock, flags);
4272 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
4273 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4274
4275 out_unlock:
4276 rcu_read_unlock();
4277 put_online_cpus();
4278
4279 return retval;
4280 }
4281
4282 /**
4283 * sys_sched_getaffinity - get the cpu affinity of a process
4284 * @pid: pid of the process
4285 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4286 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4287 */
4288 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4289 unsigned long __user *, user_mask_ptr)
4290 {
4291 int ret;
4292 cpumask_var_t mask;
4293
4294 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4295 return -EINVAL;
4296 if (len & (sizeof(unsigned long)-1))
4297 return -EINVAL;
4298
4299 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4300 return -ENOMEM;
4301
4302 ret = sched_getaffinity(pid, mask);
4303 if (ret == 0) {
4304 size_t retlen = min_t(size_t, len, cpumask_size());
4305
4306 if (copy_to_user(user_mask_ptr, mask, retlen))
4307 ret = -EFAULT;
4308 else
4309 ret = retlen;
4310 }
4311 free_cpumask_var(mask);
4312
4313 return ret;
4314 }
4315
4316 /**
4317 * sys_sched_yield - yield the current processor to other threads.
4318 *
4319 * This function yields the current CPU to other tasks. If there are no
4320 * other threads running on this CPU then this function will return.
4321 */
4322 SYSCALL_DEFINE0(sched_yield)
4323 {
4324 struct rq *rq = this_rq_lock();
4325
4326 schedstat_inc(rq, yld_count);
4327 current->sched_class->yield_task(rq);
4328
4329 /*
4330 * Since we are going to call schedule() anyway, there's
4331 * no need to preempt or enable interrupts:
4332 */
4333 __release(rq->lock);
4334 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4335 do_raw_spin_unlock(&rq->lock);
4336 sched_preempt_enable_no_resched();
4337
4338 schedule();
4339
4340 return 0;
4341 }
4342
4343 static inline int should_resched(void)
4344 {
4345 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
4346 }
4347
4348 static void __cond_resched(void)
4349 {
4350 add_preempt_count(PREEMPT_ACTIVE);
4351 __schedule();
4352 sub_preempt_count(PREEMPT_ACTIVE);
4353 }
4354
4355 int __sched _cond_resched(void)
4356 {
4357 if (should_resched()) {
4358 __cond_resched();
4359 return 1;
4360 }
4361 return 0;
4362 }
4363 EXPORT_SYMBOL(_cond_resched);
4364
4365 /*
4366 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4367 * call schedule, and on return reacquire the lock.
4368 *
4369 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4370 * operations here to prevent schedule() from being called twice (once via
4371 * spin_unlock(), once by hand).
4372 */
4373 int __cond_resched_lock(spinlock_t *lock)
4374 {
4375 int resched = should_resched();
4376 int ret = 0;
4377
4378 lockdep_assert_held(lock);
4379
4380 if (spin_needbreak(lock) || resched) {
4381 spin_unlock(lock);
4382 if (resched)
4383 __cond_resched();
4384 else
4385 cpu_relax();
4386 ret = 1;
4387 spin_lock(lock);
4388 }
4389 return ret;
4390 }
4391 EXPORT_SYMBOL(__cond_resched_lock);
4392
4393 int __sched __cond_resched_softirq(void)
4394 {
4395 BUG_ON(!in_softirq());
4396
4397 if (should_resched()) {
4398 local_bh_enable();
4399 __cond_resched();
4400 local_bh_disable();
4401 return 1;
4402 }
4403 return 0;
4404 }
4405 EXPORT_SYMBOL(__cond_resched_softirq);
4406
4407 /**
4408 * yield - yield the current processor to other threads.
4409 *
4410 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4411 *
4412 * The scheduler is at all times free to pick the calling task as the most
4413 * eligible task to run, if removing the yield() call from your code breaks
4414 * it, its already broken.
4415 *
4416 * Typical broken usage is:
4417 *
4418 * while (!event)
4419 * yield();
4420 *
4421 * where one assumes that yield() will let 'the other' process run that will
4422 * make event true. If the current task is a SCHED_FIFO task that will never
4423 * happen. Never use yield() as a progress guarantee!!
4424 *
4425 * If you want to use yield() to wait for something, use wait_event().
4426 * If you want to use yield() to be 'nice' for others, use cond_resched().
4427 * If you still want to use yield(), do not!
4428 */
4429 void __sched yield(void)
4430 {
4431 set_current_state(TASK_RUNNING);
4432 sys_sched_yield();
4433 }
4434 EXPORT_SYMBOL(yield);
4435
4436 /**
4437 * yield_to - yield the current processor to another thread in
4438 * your thread group, or accelerate that thread toward the
4439 * processor it's on.
4440 * @p: target task
4441 * @preempt: whether task preemption is allowed or not
4442 *
4443 * It's the caller's job to ensure that the target task struct
4444 * can't go away on us before we can do any checks.
4445 *
4446 * Returns:
4447 * true (>0) if we indeed boosted the target task.
4448 * false (0) if we failed to boost the target.
4449 * -ESRCH if there's no task to yield to.
4450 */
4451 bool __sched yield_to(struct task_struct *p, bool preempt)
4452 {
4453 struct task_struct *curr = current;
4454 struct rq *rq, *p_rq;
4455 unsigned long flags;
4456 int yielded = 0;
4457
4458 local_irq_save(flags);
4459 rq = this_rq();
4460
4461 again:
4462 p_rq = task_rq(p);
4463 /*
4464 * If we're the only runnable task on the rq and target rq also
4465 * has only one task, there's absolutely no point in yielding.
4466 */
4467 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4468 yielded = -ESRCH;
4469 goto out_irq;
4470 }
4471
4472 double_rq_lock(rq, p_rq);
4473 while (task_rq(p) != p_rq) {
4474 double_rq_unlock(rq, p_rq);
4475 goto again;
4476 }
4477
4478 if (!curr->sched_class->yield_to_task)
4479 goto out_unlock;
4480
4481 if (curr->sched_class != p->sched_class)
4482 goto out_unlock;
4483
4484 if (task_running(p_rq, p) || p->state)
4485 goto out_unlock;
4486
4487 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
4488 if (yielded) {
4489 schedstat_inc(rq, yld_count);
4490 /*
4491 * Make p's CPU reschedule; pick_next_entity takes care of
4492 * fairness.
4493 */
4494 if (preempt && rq != p_rq)
4495 resched_task(p_rq->curr);
4496 }
4497
4498 out_unlock:
4499 double_rq_unlock(rq, p_rq);
4500 out_irq:
4501 local_irq_restore(flags);
4502
4503 if (yielded > 0)
4504 schedule();
4505
4506 return yielded;
4507 }
4508 EXPORT_SYMBOL_GPL(yield_to);
4509
4510 /*
4511 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4512 * that process accounting knows that this is a task in IO wait state.
4513 */
4514 void __sched io_schedule(void)
4515 {
4516 struct rq *rq = raw_rq();
4517
4518 delayacct_blkio_start();
4519 atomic_inc(&rq->nr_iowait);
4520 blk_flush_plug(current);
4521 current->in_iowait = 1;
4522 schedule();
4523 current->in_iowait = 0;
4524 atomic_dec(&rq->nr_iowait);
4525 delayacct_blkio_end();
4526 }
4527 EXPORT_SYMBOL(io_schedule);
4528
4529 long __sched io_schedule_timeout(long timeout)
4530 {
4531 struct rq *rq = raw_rq();
4532 long ret;
4533
4534 delayacct_blkio_start();
4535 atomic_inc(&rq->nr_iowait);
4536 blk_flush_plug(current);
4537 current->in_iowait = 1;
4538 ret = schedule_timeout(timeout);
4539 current->in_iowait = 0;
4540 atomic_dec(&rq->nr_iowait);
4541 delayacct_blkio_end();
4542 return ret;
4543 }
4544
4545 /**
4546 * sys_sched_get_priority_max - return maximum RT priority.
4547 * @policy: scheduling class.
4548 *
4549 * this syscall returns the maximum rt_priority that can be used
4550 * by a given scheduling class.
4551 */
4552 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
4553 {
4554 int ret = -EINVAL;
4555
4556 switch (policy) {
4557 case SCHED_FIFO:
4558 case SCHED_RR:
4559 ret = MAX_USER_RT_PRIO-1;
4560 break;
4561 case SCHED_NORMAL:
4562 case SCHED_BATCH:
4563 case SCHED_IDLE:
4564 ret = 0;
4565 break;
4566 }
4567 return ret;
4568 }
4569
4570 /**
4571 * sys_sched_get_priority_min - return minimum RT priority.
4572 * @policy: scheduling class.
4573 *
4574 * this syscall returns the minimum rt_priority that can be used
4575 * by a given scheduling class.
4576 */
4577 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
4578 {
4579 int ret = -EINVAL;
4580
4581 switch (policy) {
4582 case SCHED_FIFO:
4583 case SCHED_RR:
4584 ret = 1;
4585 break;
4586 case SCHED_NORMAL:
4587 case SCHED_BATCH:
4588 case SCHED_IDLE:
4589 ret = 0;
4590 }
4591 return ret;
4592 }
4593
4594 /**
4595 * sys_sched_rr_get_interval - return the default timeslice of a process.
4596 * @pid: pid of the process.
4597 * @interval: userspace pointer to the timeslice value.
4598 *
4599 * this syscall writes the default timeslice value of a given process
4600 * into the user-space timespec buffer. A value of '0' means infinity.
4601 */
4602 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
4603 struct timespec __user *, interval)
4604 {
4605 struct task_struct *p;
4606 unsigned int time_slice;
4607 unsigned long flags;
4608 struct rq *rq;
4609 int retval;
4610 struct timespec t;
4611
4612 if (pid < 0)
4613 return -EINVAL;
4614
4615 retval = -ESRCH;
4616 rcu_read_lock();
4617 p = find_process_by_pid(pid);
4618 if (!p)
4619 goto out_unlock;
4620
4621 retval = security_task_getscheduler(p);
4622 if (retval)
4623 goto out_unlock;
4624
4625 rq = task_rq_lock(p, &flags);
4626 time_slice = p->sched_class->get_rr_interval(rq, p);
4627 task_rq_unlock(rq, p, &flags);
4628
4629 rcu_read_unlock();
4630 jiffies_to_timespec(time_slice, &t);
4631 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4632 return retval;
4633
4634 out_unlock:
4635 rcu_read_unlock();
4636 return retval;
4637 }
4638
4639 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
4640
4641 void sched_show_task(struct task_struct *p)
4642 {
4643 unsigned long free = 0;
4644 int ppid;
4645 unsigned state;
4646
4647 state = p->state ? __ffs(p->state) + 1 : 0;
4648 printk(KERN_INFO "%-15.15s %c", p->comm,
4649 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4650 #if BITS_PER_LONG == 32
4651 if (state == TASK_RUNNING)
4652 printk(KERN_CONT " running ");
4653 else
4654 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
4655 #else
4656 if (state == TASK_RUNNING)
4657 printk(KERN_CONT " running task ");
4658 else
4659 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
4660 #endif
4661 #ifdef CONFIG_DEBUG_STACK_USAGE
4662 free = stack_not_used(p);
4663 #endif
4664 rcu_read_lock();
4665 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4666 rcu_read_unlock();
4667 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4668 task_pid_nr(p), ppid,
4669 (unsigned long)task_thread_info(p)->flags);
4670
4671 show_stack(p, NULL);
4672 }
4673
4674 void show_state_filter(unsigned long state_filter)
4675 {
4676 struct task_struct *g, *p;
4677
4678 #if BITS_PER_LONG == 32
4679 printk(KERN_INFO
4680 " task PC stack pid father\n");
4681 #else
4682 printk(KERN_INFO
4683 " task PC stack pid father\n");
4684 #endif
4685 rcu_read_lock();
4686 do_each_thread(g, p) {
4687 /*
4688 * reset the NMI-timeout, listing all files on a slow
4689 * console might take a lot of time:
4690 */
4691 touch_nmi_watchdog();
4692 if (!state_filter || (p->state & state_filter))
4693 sched_show_task(p);
4694 } while_each_thread(g, p);
4695
4696 touch_all_softlockup_watchdogs();
4697
4698 #ifdef CONFIG_SCHED_DEBUG
4699 sysrq_sched_debug_show();
4700 #endif
4701 rcu_read_unlock();
4702 /*
4703 * Only show locks if all tasks are dumped:
4704 */
4705 if (!state_filter)
4706 debug_show_all_locks();
4707 }
4708
4709 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4710 {
4711 idle->sched_class = &idle_sched_class;
4712 }
4713
4714 /**
4715 * init_idle - set up an idle thread for a given CPU
4716 * @idle: task in question
4717 * @cpu: cpu the idle task belongs to
4718 *
4719 * NOTE: this function does not set the idle thread's NEED_RESCHED
4720 * flag, to make booting more robust.
4721 */
4722 void __cpuinit init_idle(struct task_struct *idle, int cpu)
4723 {
4724 struct rq *rq = cpu_rq(cpu);
4725 unsigned long flags;
4726
4727 raw_spin_lock_irqsave(&rq->lock, flags);
4728
4729 __sched_fork(idle);
4730 idle->state = TASK_RUNNING;
4731 idle->se.exec_start = sched_clock();
4732
4733 do_set_cpus_allowed(idle, cpumask_of(cpu));
4734 /*
4735 * We're having a chicken and egg problem, even though we are
4736 * holding rq->lock, the cpu isn't yet set to this cpu so the
4737 * lockdep check in task_group() will fail.
4738 *
4739 * Similar case to sched_fork(). / Alternatively we could
4740 * use task_rq_lock() here and obtain the other rq->lock.
4741 *
4742 * Silence PROVE_RCU
4743 */
4744 rcu_read_lock();
4745 __set_task_cpu(idle, cpu);
4746 rcu_read_unlock();
4747
4748 rq->curr = rq->idle = idle;
4749 #if defined(CONFIG_SMP)
4750 idle->on_cpu = 1;
4751 #endif
4752 raw_spin_unlock_irqrestore(&rq->lock, flags);
4753
4754 /* Set the preempt count _outside_ the spinlocks! */
4755 task_thread_info(idle)->preempt_count = 0;
4756
4757 /*
4758 * The idle tasks have their own, simple scheduling class:
4759 */
4760 idle->sched_class = &idle_sched_class;
4761 ftrace_graph_init_idle_task(idle, cpu);
4762 vtime_init_idle(idle);
4763 #if defined(CONFIG_SMP)
4764 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
4765 #endif
4766 }
4767
4768 #ifdef CONFIG_SMP
4769 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
4770 {
4771 if (p->sched_class && p->sched_class->set_cpus_allowed)
4772 p->sched_class->set_cpus_allowed(p, new_mask);
4773
4774 cpumask_copy(&p->cpus_allowed, new_mask);
4775 p->nr_cpus_allowed = cpumask_weight(new_mask);
4776 }
4777
4778 /*
4779 * This is how migration works:
4780 *
4781 * 1) we invoke migration_cpu_stop() on the target CPU using
4782 * stop_one_cpu().
4783 * 2) stopper starts to run (implicitly forcing the migrated thread
4784 * off the CPU)
4785 * 3) it checks whether the migrated task is still in the wrong runqueue.
4786 * 4) if it's in the wrong runqueue then the migration thread removes
4787 * it and puts it into the right queue.
4788 * 5) stopper completes and stop_one_cpu() returns and the migration
4789 * is done.
4790 */
4791
4792 /*
4793 * Change a given task's CPU affinity. Migrate the thread to a
4794 * proper CPU and schedule it away if the CPU it's executing on
4795 * is removed from the allowed bitmask.
4796 *
4797 * NOTE: the caller must have a valid reference to the task, the
4798 * task must not exit() & deallocate itself prematurely. The
4799 * call is not atomic; no spinlocks may be held.
4800 */
4801 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
4802 {
4803 unsigned long flags;
4804 struct rq *rq;
4805 unsigned int dest_cpu;
4806 int ret = 0;
4807
4808 rq = task_rq_lock(p, &flags);
4809
4810 if (cpumask_equal(&p->cpus_allowed, new_mask))
4811 goto out;
4812
4813 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
4814 ret = -EINVAL;
4815 goto out;
4816 }
4817
4818 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current)) {
4819 ret = -EINVAL;
4820 goto out;
4821 }
4822
4823 do_set_cpus_allowed(p, new_mask);
4824
4825 /* Can the task run on the task's current CPU? If so, we're done */
4826 if (cpumask_test_cpu(task_cpu(p), new_mask))
4827 goto out;
4828
4829 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
4830 if (p->on_rq) {
4831 struct migration_arg arg = { p, dest_cpu };
4832 /* Need help from migration thread: drop lock and wait. */
4833 task_rq_unlock(rq, p, &flags);
4834 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
4835 tlb_migrate_finish(p->mm);
4836 return 0;
4837 }
4838 out:
4839 task_rq_unlock(rq, p, &flags);
4840
4841 return ret;
4842 }
4843 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
4844
4845 /*
4846 * Move (not current) task off this cpu, onto dest cpu. We're doing
4847 * this because either it can't run here any more (set_cpus_allowed()
4848 * away from this CPU, or CPU going down), or because we're
4849 * attempting to rebalance this task on exec (sched_exec).
4850 *
4851 * So we race with normal scheduler movements, but that's OK, as long
4852 * as the task is no longer on this CPU.
4853 *
4854 * Returns non-zero if task was successfully migrated.
4855 */
4856 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4857 {
4858 struct rq *rq_dest, *rq_src;
4859 int ret = 0;
4860
4861 if (unlikely(!cpu_active(dest_cpu)))
4862 return ret;
4863
4864 rq_src = cpu_rq(src_cpu);
4865 rq_dest = cpu_rq(dest_cpu);
4866
4867 raw_spin_lock(&p->pi_lock);
4868 double_rq_lock(rq_src, rq_dest);
4869 /* Already moved. */
4870 if (task_cpu(p) != src_cpu)
4871 goto done;
4872 /* Affinity changed (again). */
4873 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
4874 goto fail;
4875
4876 /*
4877 * If we're not on a rq, the next wake-up will ensure we're
4878 * placed properly.
4879 */
4880 if (p->on_rq) {
4881 dequeue_task(rq_src, p, 0);
4882 set_task_cpu(p, dest_cpu);
4883 enqueue_task(rq_dest, p, 0);
4884 check_preempt_curr(rq_dest, p, 0);
4885 }
4886 done:
4887 ret = 1;
4888 fail:
4889 double_rq_unlock(rq_src, rq_dest);
4890 raw_spin_unlock(&p->pi_lock);
4891 return ret;
4892 }
4893
4894 /*
4895 * migration_cpu_stop - this will be executed by a highprio stopper thread
4896 * and performs thread migration by bumping thread off CPU then
4897 * 'pushing' onto another runqueue.
4898 */
4899 static int migration_cpu_stop(void *data)
4900 {
4901 struct migration_arg *arg = data;
4902
4903 /*
4904 * The original target cpu might have gone down and we might
4905 * be on another cpu but it doesn't matter.
4906 */
4907 local_irq_disable();
4908 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
4909 local_irq_enable();
4910 return 0;
4911 }
4912
4913 #ifdef CONFIG_HOTPLUG_CPU
4914
4915 /*
4916 * Ensures that the idle task is using init_mm right before its cpu goes
4917 * offline.
4918 */
4919 void idle_task_exit(void)
4920 {
4921 struct mm_struct *mm = current->active_mm;
4922
4923 BUG_ON(cpu_online(smp_processor_id()));
4924
4925 if (mm != &init_mm)
4926 switch_mm(mm, &init_mm, current);
4927 mmdrop(mm);
4928 }
4929
4930 /*
4931 * Since this CPU is going 'away' for a while, fold any nr_active delta
4932 * we might have. Assumes we're called after migrate_tasks() so that the
4933 * nr_active count is stable.
4934 *
4935 * Also see the comment "Global load-average calculations".
4936 */
4937 static void calc_load_migrate(struct rq *rq)
4938 {
4939 long delta = calc_load_fold_active(rq);
4940 if (delta)
4941 atomic_long_add(delta, &calc_load_tasks);
4942 }
4943
4944 /*
4945 * Migrate all tasks from the rq, sleeping tasks will be migrated by
4946 * try_to_wake_up()->select_task_rq().
4947 *
4948 * Called with rq->lock held even though we'er in stop_machine() and
4949 * there's no concurrency possible, we hold the required locks anyway
4950 * because of lock validation efforts.
4951 */
4952 static void migrate_tasks(unsigned int dead_cpu)
4953 {
4954 struct rq *rq = cpu_rq(dead_cpu);
4955 struct task_struct *next, *stop = rq->stop;
4956 int dest_cpu;
4957
4958 /*
4959 * Fudge the rq selection such that the below task selection loop
4960 * doesn't get stuck on the currently eligible stop task.
4961 *
4962 * We're currently inside stop_machine() and the rq is either stuck
4963 * in the stop_machine_cpu_stop() loop, or we're executing this code,
4964 * either way we should never end up calling schedule() until we're
4965 * done here.
4966 */
4967 rq->stop = NULL;
4968
4969 for ( ; ; ) {
4970 /*
4971 * There's this thread running, bail when that's the only
4972 * remaining thread.
4973 */
4974 if (rq->nr_running == 1)
4975 break;
4976
4977 next = pick_next_task(rq);
4978 BUG_ON(!next);
4979 next->sched_class->put_prev_task(rq, next);
4980
4981 /* Find suitable destination for @next, with force if needed. */
4982 dest_cpu = select_fallback_rq(dead_cpu, next);
4983 raw_spin_unlock(&rq->lock);
4984
4985 __migrate_task(next, dead_cpu, dest_cpu);
4986
4987 raw_spin_lock(&rq->lock);
4988 }
4989
4990 rq->stop = stop;
4991 }
4992
4993 #endif /* CONFIG_HOTPLUG_CPU */
4994
4995 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
4996
4997 static struct ctl_table sd_ctl_dir[] = {
4998 {
4999 .procname = "sched_domain",
5000 .mode = 0555,
5001 },
5002 {}
5003 };
5004
5005 static struct ctl_table sd_ctl_root[] = {
5006 {
5007 .procname = "kernel",
5008 .mode = 0555,
5009 .child = sd_ctl_dir,
5010 },
5011 {}
5012 };
5013
5014 static struct ctl_table *sd_alloc_ctl_entry(int n)
5015 {
5016 struct ctl_table *entry =
5017 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5018
5019 return entry;
5020 }
5021
5022 static void sd_free_ctl_entry(struct ctl_table **tablep)
5023 {
5024 struct ctl_table *entry;
5025
5026 /*
5027 * In the intermediate directories, both the child directory and
5028 * procname are dynamically allocated and could fail but the mode
5029 * will always be set. In the lowest directory the names are
5030 * static strings and all have proc handlers.
5031 */
5032 for (entry = *tablep; entry->mode; entry++) {
5033 if (entry->child)
5034 sd_free_ctl_entry(&entry->child);
5035 if (entry->proc_handler == NULL)
5036 kfree(entry->procname);
5037 }
5038
5039 kfree(*tablep);
5040 *tablep = NULL;
5041 }
5042
5043 static int min_load_idx = 0;
5044 static int max_load_idx = CPU_LOAD_IDX_MAX;
5045
5046 static void
5047 set_table_entry(struct ctl_table *entry,
5048 const char *procname, void *data, int maxlen,
5049 umode_t mode, proc_handler *proc_handler,
5050 bool load_idx)
5051 {
5052 entry->procname = procname;
5053 entry->data = data;
5054 entry->maxlen = maxlen;
5055 entry->mode = mode;
5056 entry->proc_handler = proc_handler;
5057
5058 if (load_idx) {
5059 entry->extra1 = &min_load_idx;
5060 entry->extra2 = &max_load_idx;
5061 }
5062 }
5063
5064 static struct ctl_table *
5065 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5066 {
5067 struct ctl_table *table = sd_alloc_ctl_entry(13);
5068
5069 if (table == NULL)
5070 return NULL;
5071
5072 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5073 sizeof(long), 0644, proc_doulongvec_minmax, false);
5074 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5075 sizeof(long), 0644, proc_doulongvec_minmax, false);
5076 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5077 sizeof(int), 0644, proc_dointvec_minmax, true);
5078 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5079 sizeof(int), 0644, proc_dointvec_minmax, true);
5080 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5081 sizeof(int), 0644, proc_dointvec_minmax, true);
5082 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5083 sizeof(int), 0644, proc_dointvec_minmax, true);
5084 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5085 sizeof(int), 0644, proc_dointvec_minmax, true);
5086 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5087 sizeof(int), 0644, proc_dointvec_minmax, false);
5088 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5089 sizeof(int), 0644, proc_dointvec_minmax, false);
5090 set_table_entry(&table[9], "cache_nice_tries",
5091 &sd->cache_nice_tries,
5092 sizeof(int), 0644, proc_dointvec_minmax, false);
5093 set_table_entry(&table[10], "flags", &sd->flags,
5094 sizeof(int), 0644, proc_dointvec_minmax, false);
5095 set_table_entry(&table[11], "name", sd->name,
5096 CORENAME_MAX_SIZE, 0444, proc_dostring, false);
5097 /* &table[12] is terminator */
5098
5099 return table;
5100 }
5101
5102 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5103 {
5104 struct ctl_table *entry, *table;
5105 struct sched_domain *sd;
5106 int domain_num = 0, i;
5107 char buf[32];
5108
5109 for_each_domain(cpu, sd)
5110 domain_num++;
5111 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5112 if (table == NULL)
5113 return NULL;
5114
5115 i = 0;
5116 for_each_domain(cpu, sd) {
5117 snprintf(buf, 32, "domain%d", i);
5118 entry->procname = kstrdup(buf, GFP_KERNEL);
5119 entry->mode = 0555;
5120 entry->child = sd_alloc_ctl_domain_table(sd);
5121 entry++;
5122 i++;
5123 }
5124 return table;
5125 }
5126
5127 static struct ctl_table_header *sd_sysctl_header;
5128 static void register_sched_domain_sysctl(void)
5129 {
5130 int i, cpu_num = num_possible_cpus();
5131 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5132 char buf[32];
5133
5134 WARN_ON(sd_ctl_dir[0].child);
5135 sd_ctl_dir[0].child = entry;
5136
5137 if (entry == NULL)
5138 return;
5139
5140 for_each_possible_cpu(i) {
5141 snprintf(buf, 32, "cpu%d", i);
5142 entry->procname = kstrdup(buf, GFP_KERNEL);
5143 entry->mode = 0555;
5144 entry->child = sd_alloc_ctl_cpu_table(i);
5145 entry++;
5146 }
5147
5148 WARN_ON(sd_sysctl_header);
5149 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5150 }
5151
5152 /* may be called multiple times per register */
5153 static void unregister_sched_domain_sysctl(void)
5154 {
5155 if (sd_sysctl_header)
5156 unregister_sysctl_table(sd_sysctl_header);
5157 sd_sysctl_header = NULL;
5158 if (sd_ctl_dir[0].child)
5159 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5160 }
5161 #else
5162 static void register_sched_domain_sysctl(void)
5163 {
5164 }
5165 static void unregister_sched_domain_sysctl(void)
5166 {
5167 }
5168 #endif
5169
5170 static void set_rq_online(struct rq *rq)
5171 {
5172 if (!rq->online) {
5173 const struct sched_class *class;
5174
5175 cpumask_set_cpu(rq->cpu, rq->rd->online);
5176 rq->online = 1;
5177
5178 for_each_class(class) {
5179 if (class->rq_online)
5180 class->rq_online(rq);
5181 }
5182 }
5183 }
5184
5185 static void set_rq_offline(struct rq *rq)
5186 {
5187 if (rq->online) {
5188 const struct sched_class *class;
5189
5190 for_each_class(class) {
5191 if (class->rq_offline)
5192 class->rq_offline(rq);
5193 }
5194
5195 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5196 rq->online = 0;
5197 }
5198 }
5199
5200 /*
5201 * migration_call - callback that gets triggered when a CPU is added.
5202 * Here we can start up the necessary migration thread for the new CPU.
5203 */
5204 static int __cpuinit
5205 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5206 {
5207 int cpu = (long)hcpu;
5208 unsigned long flags;
5209 struct rq *rq = cpu_rq(cpu);
5210
5211 switch (action & ~CPU_TASKS_FROZEN) {
5212
5213 case CPU_UP_PREPARE:
5214 rq->calc_load_update = calc_load_update;
5215 break;
5216
5217 case CPU_ONLINE:
5218 /* Update our root-domain */
5219 raw_spin_lock_irqsave(&rq->lock, flags);
5220 if (rq->rd) {
5221 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5222
5223 set_rq_online(rq);
5224 }
5225 raw_spin_unlock_irqrestore(&rq->lock, flags);
5226 break;
5227
5228 #ifdef CONFIG_HOTPLUG_CPU
5229 case CPU_DYING:
5230 sched_ttwu_pending();
5231 /* Update our root-domain */
5232 raw_spin_lock_irqsave(&rq->lock, flags);
5233 if (rq->rd) {
5234 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5235 set_rq_offline(rq);
5236 }
5237 migrate_tasks(cpu);
5238 BUG_ON(rq->nr_running != 1); /* the migration thread */
5239 raw_spin_unlock_irqrestore(&rq->lock, flags);
5240 break;
5241
5242 case CPU_DEAD:
5243 calc_load_migrate(rq);
5244 break;
5245 #endif
5246 }
5247
5248 update_max_interval();
5249
5250 return NOTIFY_OK;
5251 }
5252
5253 /*
5254 * Register at high priority so that task migration (migrate_all_tasks)
5255 * happens before everything else. This has to be lower priority than
5256 * the notifier in the perf_event subsystem, though.
5257 */
5258 static struct notifier_block __cpuinitdata migration_notifier = {
5259 .notifier_call = migration_call,
5260 .priority = CPU_PRI_MIGRATION,
5261 };
5262
5263 static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
5264 unsigned long action, void *hcpu)
5265 {
5266 switch (action & ~CPU_TASKS_FROZEN) {
5267 case CPU_STARTING:
5268 case CPU_DOWN_FAILED:
5269 set_cpu_active((long)hcpu, true);
5270 return NOTIFY_OK;
5271 default:
5272 return NOTIFY_DONE;
5273 }
5274 }
5275
5276 static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
5277 unsigned long action, void *hcpu)
5278 {
5279 switch (action & ~CPU_TASKS_FROZEN) {
5280 case CPU_DOWN_PREPARE:
5281 set_cpu_active((long)hcpu, false);
5282 return NOTIFY_OK;
5283 default:
5284 return NOTIFY_DONE;
5285 }
5286 }
5287
5288 static int __init migration_init(void)
5289 {
5290 void *cpu = (void *)(long)smp_processor_id();
5291 int err;
5292
5293 /* Initialize migration for the boot CPU */
5294 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5295 BUG_ON(err == NOTIFY_BAD);
5296 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5297 register_cpu_notifier(&migration_notifier);
5298
5299 /* Register cpu active notifiers */
5300 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5301 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5302
5303 return 0;
5304 }
5305 early_initcall(migration_init);
5306 #endif
5307
5308 #ifdef CONFIG_SMP
5309
5310 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5311
5312 #ifdef CONFIG_SCHED_DEBUG
5313
5314 static __read_mostly int sched_debug_enabled;
5315
5316 static int __init sched_debug_setup(char *str)
5317 {
5318 sched_debug_enabled = 1;
5319
5320 return 0;
5321 }
5322 early_param("sched_debug", sched_debug_setup);
5323
5324 static inline bool sched_debug(void)
5325 {
5326 return sched_debug_enabled;
5327 }
5328
5329 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5330 struct cpumask *groupmask)
5331 {
5332 struct sched_group *group = sd->groups;
5333 char str[256];
5334
5335 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
5336 cpumask_clear(groupmask);
5337
5338 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5339
5340 if (!(sd->flags & SD_LOAD_BALANCE)) {
5341 printk("does not load-balance\n");
5342 if (sd->parent)
5343 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5344 " has parent");
5345 return -1;
5346 }
5347
5348 printk(KERN_CONT "span %s level %s\n", str, sd->name);
5349
5350 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5351 printk(KERN_ERR "ERROR: domain->span does not contain "
5352 "CPU%d\n", cpu);
5353 }
5354 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5355 printk(KERN_ERR "ERROR: domain->groups does not contain"
5356 " CPU%d\n", cpu);
5357 }
5358
5359 printk(KERN_DEBUG "%*s groups:", level + 1, "");
5360 do {
5361 if (!group) {
5362 printk("\n");
5363 printk(KERN_ERR "ERROR: group is NULL\n");
5364 break;
5365 }
5366
5367 /*
5368 * Even though we initialize ->power to something semi-sane,
5369 * we leave power_orig unset. This allows us to detect if
5370 * domain iteration is still funny without causing /0 traps.
5371 */
5372 if (!group->sgp->power_orig) {
5373 printk(KERN_CONT "\n");
5374 printk(KERN_ERR "ERROR: domain->cpu_power not "
5375 "set\n");
5376 break;
5377 }
5378
5379 if (!cpumask_weight(sched_group_cpus(group))) {
5380 printk(KERN_CONT "\n");
5381 printk(KERN_ERR "ERROR: empty group\n");
5382 break;
5383 }
5384
5385 if (!(sd->flags & SD_OVERLAP) &&
5386 cpumask_intersects(groupmask, sched_group_cpus(group))) {
5387 printk(KERN_CONT "\n");
5388 printk(KERN_ERR "ERROR: repeated CPUs\n");
5389 break;
5390 }
5391
5392 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5393
5394 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
5395
5396 printk(KERN_CONT " %s", str);
5397 if (group->sgp->power != SCHED_POWER_SCALE) {
5398 printk(KERN_CONT " (cpu_power = %d)",
5399 group->sgp->power);
5400 }
5401
5402 group = group->next;
5403 } while (group != sd->groups);
5404 printk(KERN_CONT "\n");
5405
5406 if (!cpumask_equal(sched_domain_span(sd), groupmask))
5407 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5408
5409 if (sd->parent &&
5410 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5411 printk(KERN_ERR "ERROR: parent span is not a superset "
5412 "of domain->span\n");
5413 return 0;
5414 }
5415
5416 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5417 {
5418 int level = 0;
5419
5420 if (!sched_debug_enabled)
5421 return;
5422
5423 if (!sd) {
5424 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5425 return;
5426 }
5427
5428 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5429
5430 for (;;) {
5431 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5432 break;
5433 level++;
5434 sd = sd->parent;
5435 if (!sd)
5436 break;
5437 }
5438 }
5439 #else /* !CONFIG_SCHED_DEBUG */
5440 # define sched_domain_debug(sd, cpu) do { } while (0)
5441 static inline bool sched_debug(void)
5442 {
5443 return false;
5444 }
5445 #endif /* CONFIG_SCHED_DEBUG */
5446
5447 static int sd_degenerate(struct sched_domain *sd)
5448 {
5449 if (cpumask_weight(sched_domain_span(sd)) == 1)
5450 return 1;
5451
5452 /* Following flags need at least 2 groups */
5453 if (sd->flags & (SD_LOAD_BALANCE |
5454 SD_BALANCE_NEWIDLE |
5455 SD_BALANCE_FORK |
5456 SD_BALANCE_EXEC |
5457 SD_SHARE_CPUPOWER |
5458 SD_SHARE_PKG_RESOURCES)) {
5459 if (sd->groups != sd->groups->next)
5460 return 0;
5461 }
5462
5463 /* Following flags don't use groups */
5464 if (sd->flags & (SD_WAKE_AFFINE))
5465 return 0;
5466
5467 return 1;
5468 }
5469
5470 static int
5471 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5472 {
5473 unsigned long cflags = sd->flags, pflags = parent->flags;
5474
5475 if (sd_degenerate(parent))
5476 return 1;
5477
5478 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5479 return 0;
5480
5481 /* Flags needing groups don't count if only 1 group in parent */
5482 if (parent->groups == parent->groups->next) {
5483 pflags &= ~(SD_LOAD_BALANCE |
5484 SD_BALANCE_NEWIDLE |
5485 SD_BALANCE_FORK |
5486 SD_BALANCE_EXEC |
5487 SD_SHARE_CPUPOWER |
5488 SD_SHARE_PKG_RESOURCES);
5489 if (nr_node_ids == 1)
5490 pflags &= ~SD_SERIALIZE;
5491 }
5492 if (~cflags & pflags)
5493 return 0;
5494
5495 return 1;
5496 }
5497
5498 static void free_rootdomain(struct rcu_head *rcu)
5499 {
5500 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5501
5502 cpupri_cleanup(&rd->cpupri);
5503 free_cpumask_var(rd->rto_mask);
5504 free_cpumask_var(rd->online);
5505 free_cpumask_var(rd->span);
5506 kfree(rd);
5507 }
5508
5509 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5510 {
5511 struct root_domain *old_rd = NULL;
5512 unsigned long flags;
5513
5514 raw_spin_lock_irqsave(&rq->lock, flags);
5515
5516 if (rq->rd) {
5517 old_rd = rq->rd;
5518
5519 if (cpumask_test_cpu(rq->cpu, old_rd->online))
5520 set_rq_offline(rq);
5521
5522 cpumask_clear_cpu(rq->cpu, old_rd->span);
5523
5524 /*
5525 * If we dont want to free the old_rt yet then
5526 * set old_rd to NULL to skip the freeing later
5527 * in this function:
5528 */
5529 if (!atomic_dec_and_test(&old_rd->refcount))
5530 old_rd = NULL;
5531 }
5532
5533 atomic_inc(&rd->refcount);
5534 rq->rd = rd;
5535
5536 cpumask_set_cpu(rq->cpu, rd->span);
5537 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
5538 set_rq_online(rq);
5539
5540 raw_spin_unlock_irqrestore(&rq->lock, flags);
5541
5542 if (old_rd)
5543 call_rcu_sched(&old_rd->rcu, free_rootdomain);
5544 }
5545
5546 static int init_rootdomain(struct root_domain *rd)
5547 {
5548 memset(rd, 0, sizeof(*rd));
5549
5550 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
5551 goto out;
5552 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
5553 goto free_span;
5554 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
5555 goto free_online;
5556
5557 if (cpupri_init(&rd->cpupri) != 0)
5558 goto free_rto_mask;
5559 return 0;
5560
5561 free_rto_mask:
5562 free_cpumask_var(rd->rto_mask);
5563 free_online:
5564 free_cpumask_var(rd->online);
5565 free_span:
5566 free_cpumask_var(rd->span);
5567 out:
5568 return -ENOMEM;
5569 }
5570
5571 /*
5572 * By default the system creates a single root-domain with all cpus as
5573 * members (mimicking the global state we have today).
5574 */
5575 struct root_domain def_root_domain;
5576
5577 static void init_defrootdomain(void)
5578 {
5579 init_rootdomain(&def_root_domain);
5580
5581 atomic_set(&def_root_domain.refcount, 1);
5582 }
5583
5584 static struct root_domain *alloc_rootdomain(void)
5585 {
5586 struct root_domain *rd;
5587
5588 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5589 if (!rd)
5590 return NULL;
5591
5592 if (init_rootdomain(rd) != 0) {
5593 kfree(rd);
5594 return NULL;
5595 }
5596
5597 return rd;
5598 }
5599
5600 static void free_sched_groups(struct sched_group *sg, int free_sgp)
5601 {
5602 struct sched_group *tmp, *first;
5603
5604 if (!sg)
5605 return;
5606
5607 first = sg;
5608 do {
5609 tmp = sg->next;
5610
5611 if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
5612 kfree(sg->sgp);
5613
5614 kfree(sg);
5615 sg = tmp;
5616 } while (sg != first);
5617 }
5618
5619 static void free_sched_domain(struct rcu_head *rcu)
5620 {
5621 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
5622
5623 /*
5624 * If its an overlapping domain it has private groups, iterate and
5625 * nuke them all.
5626 */
5627 if (sd->flags & SD_OVERLAP) {
5628 free_sched_groups(sd->groups, 1);
5629 } else if (atomic_dec_and_test(&sd->groups->ref)) {
5630 kfree(sd->groups->sgp);
5631 kfree(sd->groups);
5632 }
5633 kfree(sd);
5634 }
5635
5636 static void destroy_sched_domain(struct sched_domain *sd, int cpu)
5637 {
5638 call_rcu(&sd->rcu, free_sched_domain);
5639 }
5640
5641 static void destroy_sched_domains(struct sched_domain *sd, int cpu)
5642 {
5643 for (; sd; sd = sd->parent)
5644 destroy_sched_domain(sd, cpu);
5645 }
5646
5647 /*
5648 * Keep a special pointer to the highest sched_domain that has
5649 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
5650 * allows us to avoid some pointer chasing select_idle_sibling().
5651 *
5652 * Also keep a unique ID per domain (we use the first cpu number in
5653 * the cpumask of the domain), this allows us to quickly tell if
5654 * two cpus are in the same cache domain, see cpus_share_cache().
5655 */
5656 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
5657 DEFINE_PER_CPU(int, sd_llc_id);
5658
5659 static void update_top_cache_domain(int cpu)
5660 {
5661 struct sched_domain *sd;
5662 int id = cpu;
5663
5664 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
5665 if (sd)
5666 id = cpumask_first(sched_domain_span(sd));
5667
5668 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
5669 per_cpu(sd_llc_id, cpu) = id;
5670 }
5671
5672 /*
5673 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5674 * hold the hotplug lock.
5675 */
5676 static void
5677 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
5678 {
5679 struct rq *rq = cpu_rq(cpu);
5680 struct sched_domain *tmp;
5681
5682 /* Remove the sched domains which do not contribute to scheduling. */
5683 for (tmp = sd; tmp; ) {
5684 struct sched_domain *parent = tmp->parent;
5685 if (!parent)
5686 break;
5687
5688 if (sd_parent_degenerate(tmp, parent)) {
5689 tmp->parent = parent->parent;
5690 if (parent->parent)
5691 parent->parent->child = tmp;
5692 destroy_sched_domain(parent, cpu);
5693 } else
5694 tmp = tmp->parent;
5695 }
5696
5697 if (sd && sd_degenerate(sd)) {
5698 tmp = sd;
5699 sd = sd->parent;
5700 destroy_sched_domain(tmp, cpu);
5701 if (sd)
5702 sd->child = NULL;
5703 }
5704
5705 sched_domain_debug(sd, cpu);
5706
5707 rq_attach_root(rq, rd);
5708 tmp = rq->sd;
5709 rcu_assign_pointer(rq->sd, sd);
5710 destroy_sched_domains(tmp, cpu);
5711
5712 update_top_cache_domain(cpu);
5713 }
5714
5715 /* cpus with isolated domains */
5716 static cpumask_var_t cpu_isolated_map;
5717
5718 /* Setup the mask of cpus configured for isolated domains */
5719 static int __init isolated_cpu_setup(char *str)
5720 {
5721 alloc_bootmem_cpumask_var(&cpu_isolated_map);
5722 cpulist_parse(str, cpu_isolated_map);
5723 return 1;
5724 }
5725
5726 __setup("isolcpus=", isolated_cpu_setup);
5727
5728 static const struct cpumask *cpu_cpu_mask(int cpu)
5729 {
5730 return cpumask_of_node(cpu_to_node(cpu));
5731 }
5732
5733 struct sd_data {
5734 struct sched_domain **__percpu sd;
5735 struct sched_group **__percpu sg;
5736 struct sched_group_power **__percpu sgp;
5737 };
5738
5739 struct s_data {
5740 struct sched_domain ** __percpu sd;
5741 struct root_domain *rd;
5742 };
5743
5744 enum s_alloc {
5745 sa_rootdomain,
5746 sa_sd,
5747 sa_sd_storage,
5748 sa_none,
5749 };
5750
5751 struct sched_domain_topology_level;
5752
5753 typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
5754 typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
5755
5756 #define SDTL_OVERLAP 0x01
5757
5758 struct sched_domain_topology_level {
5759 sched_domain_init_f init;
5760 sched_domain_mask_f mask;
5761 int flags;
5762 int numa_level;
5763 struct sd_data data;
5764 };
5765
5766 /*
5767 * Build an iteration mask that can exclude certain CPUs from the upwards
5768 * domain traversal.
5769 *
5770 * Asymmetric node setups can result in situations where the domain tree is of
5771 * unequal depth, make sure to skip domains that already cover the entire
5772 * range.
5773 *
5774 * In that case build_sched_domains() will have terminated the iteration early
5775 * and our sibling sd spans will be empty. Domains should always include the
5776 * cpu they're built on, so check that.
5777 *
5778 */
5779 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
5780 {
5781 const struct cpumask *span = sched_domain_span(sd);
5782 struct sd_data *sdd = sd->private;
5783 struct sched_domain *sibling;
5784 int i;
5785
5786 for_each_cpu(i, span) {
5787 sibling = *per_cpu_ptr(sdd->sd, i);
5788 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
5789 continue;
5790
5791 cpumask_set_cpu(i, sched_group_mask(sg));
5792 }
5793 }
5794
5795 /*
5796 * Return the canonical balance cpu for this group, this is the first cpu
5797 * of this group that's also in the iteration mask.
5798 */
5799 int group_balance_cpu(struct sched_group *sg)
5800 {
5801 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
5802 }
5803
5804 static int
5805 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
5806 {
5807 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
5808 const struct cpumask *span = sched_domain_span(sd);
5809 struct cpumask *covered = sched_domains_tmpmask;
5810 struct sd_data *sdd = sd->private;
5811 struct sched_domain *child;
5812 int i;
5813
5814 cpumask_clear(covered);
5815
5816 for_each_cpu(i, span) {
5817 struct cpumask *sg_span;
5818
5819 if (cpumask_test_cpu(i, covered))
5820 continue;
5821
5822 child = *per_cpu_ptr(sdd->sd, i);
5823
5824 /* See the comment near build_group_mask(). */
5825 if (!cpumask_test_cpu(i, sched_domain_span(child)))
5826 continue;
5827
5828 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
5829 GFP_KERNEL, cpu_to_node(cpu));
5830
5831 if (!sg)
5832 goto fail;
5833
5834 sg_span = sched_group_cpus(sg);
5835 if (child->child) {
5836 child = child->child;
5837 cpumask_copy(sg_span, sched_domain_span(child));
5838 } else
5839 cpumask_set_cpu(i, sg_span);
5840
5841 cpumask_or(covered, covered, sg_span);
5842
5843 sg->sgp = *per_cpu_ptr(sdd->sgp, i);
5844 if (atomic_inc_return(&sg->sgp->ref) == 1)
5845 build_group_mask(sd, sg);
5846
5847 /*
5848 * Initialize sgp->power such that even if we mess up the
5849 * domains and no possible iteration will get us here, we won't
5850 * die on a /0 trap.
5851 */
5852 sg->sgp->power = SCHED_POWER_SCALE * cpumask_weight(sg_span);
5853
5854 /*
5855 * Make sure the first group of this domain contains the
5856 * canonical balance cpu. Otherwise the sched_domain iteration
5857 * breaks. See update_sg_lb_stats().
5858 */
5859 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
5860 group_balance_cpu(sg) == cpu)
5861 groups = sg;
5862
5863 if (!first)
5864 first = sg;
5865 if (last)
5866 last->next = sg;
5867 last = sg;
5868 last->next = first;
5869 }
5870 sd->groups = groups;
5871
5872 return 0;
5873
5874 fail:
5875 free_sched_groups(first, 0);
5876
5877 return -ENOMEM;
5878 }
5879
5880 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
5881 {
5882 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
5883 struct sched_domain *child = sd->child;
5884
5885 if (child)
5886 cpu = cpumask_first(sched_domain_span(child));
5887
5888 if (sg) {
5889 *sg = *per_cpu_ptr(sdd->sg, cpu);
5890 (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
5891 atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
5892 }
5893
5894 return cpu;
5895 }
5896
5897 /*
5898 * build_sched_groups will build a circular linked list of the groups
5899 * covered by the given span, and will set each group's ->cpumask correctly,
5900 * and ->cpu_power to 0.
5901 *
5902 * Assumes the sched_domain tree is fully constructed
5903 */
5904 static int
5905 build_sched_groups(struct sched_domain *sd, int cpu)
5906 {
5907 struct sched_group *first = NULL, *last = NULL;
5908 struct sd_data *sdd = sd->private;
5909 const struct cpumask *span = sched_domain_span(sd);
5910 struct cpumask *covered;
5911 int i;
5912
5913 get_group(cpu, sdd, &sd->groups);
5914 atomic_inc(&sd->groups->ref);
5915
5916 if (cpu != cpumask_first(sched_domain_span(sd)))
5917 return 0;
5918
5919 lockdep_assert_held(&sched_domains_mutex);
5920 covered = sched_domains_tmpmask;
5921
5922 cpumask_clear(covered);
5923
5924 for_each_cpu(i, span) {
5925 struct sched_group *sg;
5926 int group = get_group(i, sdd, &sg);
5927 int j;
5928
5929 if (cpumask_test_cpu(i, covered))
5930 continue;
5931
5932 cpumask_clear(sched_group_cpus(sg));
5933 sg->sgp->power = 0;
5934 cpumask_setall(sched_group_mask(sg));
5935
5936 for_each_cpu(j, span) {
5937 if (get_group(j, sdd, NULL) != group)
5938 continue;
5939
5940 cpumask_set_cpu(j, covered);
5941 cpumask_set_cpu(j, sched_group_cpus(sg));
5942 }
5943
5944 if (!first)
5945 first = sg;
5946 if (last)
5947 last->next = sg;
5948 last = sg;
5949 }
5950 last->next = first;
5951
5952 return 0;
5953 }
5954
5955 /*
5956 * Initialize sched groups cpu_power.
5957 *
5958 * cpu_power indicates the capacity of sched group, which is used while
5959 * distributing the load between different sched groups in a sched domain.
5960 * Typically cpu_power for all the groups in a sched domain will be same unless
5961 * there are asymmetries in the topology. If there are asymmetries, group
5962 * having more cpu_power will pickup more load compared to the group having
5963 * less cpu_power.
5964 */
5965 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
5966 {
5967 struct sched_group *sg = sd->groups;
5968
5969 WARN_ON(!sd || !sg);
5970
5971 do {
5972 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
5973 sg = sg->next;
5974 } while (sg != sd->groups);
5975
5976 if (cpu != group_balance_cpu(sg))
5977 return;
5978
5979 update_group_power(sd, cpu);
5980 atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight);
5981 }
5982
5983 int __weak arch_sd_sibling_asym_packing(void)
5984 {
5985 return 0*SD_ASYM_PACKING;
5986 }
5987
5988 /*
5989 * Initializers for schedule domains
5990 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
5991 */
5992
5993 #ifdef CONFIG_SCHED_DEBUG
5994 # define SD_INIT_NAME(sd, type) sd->name = #type
5995 #else
5996 # define SD_INIT_NAME(sd, type) do { } while (0)
5997 #endif
5998
5999 #define SD_INIT_FUNC(type) \
6000 static noinline struct sched_domain * \
6001 sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \
6002 { \
6003 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \
6004 *sd = SD_##type##_INIT; \
6005 SD_INIT_NAME(sd, type); \
6006 sd->private = &tl->data; \
6007 return sd; \
6008 }
6009
6010 SD_INIT_FUNC(CPU)
6011 #ifdef CONFIG_SCHED_SMT
6012 SD_INIT_FUNC(SIBLING)
6013 #endif
6014 #ifdef CONFIG_SCHED_MC
6015 SD_INIT_FUNC(MC)
6016 #endif
6017 #ifdef CONFIG_SCHED_BOOK
6018 SD_INIT_FUNC(BOOK)
6019 #endif
6020
6021 static int default_relax_domain_level = -1;
6022 int sched_domain_level_max;
6023
6024 static int __init setup_relax_domain_level(char *str)
6025 {
6026 if (kstrtoint(str, 0, &default_relax_domain_level))
6027 pr_warn("Unable to set relax_domain_level\n");
6028
6029 return 1;
6030 }
6031 __setup("relax_domain_level=", setup_relax_domain_level);
6032
6033 static void set_domain_attribute(struct sched_domain *sd,
6034 struct sched_domain_attr *attr)
6035 {
6036 int request;
6037
6038 if (!attr || attr->relax_domain_level < 0) {
6039 if (default_relax_domain_level < 0)
6040 return;
6041 else
6042 request = default_relax_domain_level;
6043 } else
6044 request = attr->relax_domain_level;
6045 if (request < sd->level) {
6046 /* turn off idle balance on this domain */
6047 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6048 } else {
6049 /* turn on idle balance on this domain */
6050 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6051 }
6052 }
6053
6054 static void __sdt_free(const struct cpumask *cpu_map);
6055 static int __sdt_alloc(const struct cpumask *cpu_map);
6056
6057 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6058 const struct cpumask *cpu_map)
6059 {
6060 switch (what) {
6061 case sa_rootdomain:
6062 if (!atomic_read(&d->rd->refcount))
6063 free_rootdomain(&d->rd->rcu); /* fall through */
6064 case sa_sd:
6065 free_percpu(d->sd); /* fall through */
6066 case sa_sd_storage:
6067 __sdt_free(cpu_map); /* fall through */
6068 case sa_none:
6069 break;
6070 }
6071 }
6072
6073 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6074 const struct cpumask *cpu_map)
6075 {
6076 memset(d, 0, sizeof(*d));
6077
6078 if (__sdt_alloc(cpu_map))
6079 return sa_sd_storage;
6080 d->sd = alloc_percpu(struct sched_domain *);
6081 if (!d->sd)
6082 return sa_sd_storage;
6083 d->rd = alloc_rootdomain();
6084 if (!d->rd)
6085 return sa_sd;
6086 return sa_rootdomain;
6087 }
6088
6089 /*
6090 * NULL the sd_data elements we've used to build the sched_domain and
6091 * sched_group structure so that the subsequent __free_domain_allocs()
6092 * will not free the data we're using.
6093 */
6094 static void claim_allocations(int cpu, struct sched_domain *sd)
6095 {
6096 struct sd_data *sdd = sd->private;
6097
6098 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6099 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6100
6101 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6102 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6103
6104 if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
6105 *per_cpu_ptr(sdd->sgp, cpu) = NULL;
6106 }
6107
6108 #ifdef CONFIG_SCHED_SMT
6109 static const struct cpumask *cpu_smt_mask(int cpu)
6110 {
6111 return topology_thread_cpumask(cpu);
6112 }
6113 #endif
6114
6115 /*
6116 * Topology list, bottom-up.
6117 */
6118 static struct sched_domain_topology_level default_topology[] = {
6119 #ifdef CONFIG_SCHED_SMT
6120 { sd_init_SIBLING, cpu_smt_mask, },
6121 #endif
6122 #ifdef CONFIG_SCHED_MC
6123 { sd_init_MC, cpu_coregroup_mask, },
6124 #endif
6125 #ifdef CONFIG_SCHED_BOOK
6126 { sd_init_BOOK, cpu_book_mask, },
6127 #endif
6128 { sd_init_CPU, cpu_cpu_mask, },
6129 { NULL, },
6130 };
6131
6132 static struct sched_domain_topology_level *sched_domain_topology = default_topology;
6133
6134 #ifdef CONFIG_NUMA
6135
6136 static int sched_domains_numa_levels;
6137 static int *sched_domains_numa_distance;
6138 static struct cpumask ***sched_domains_numa_masks;
6139 static int sched_domains_curr_level;
6140
6141 static inline int sd_local_flags(int level)
6142 {
6143 if (sched_domains_numa_distance[level] > RECLAIM_DISTANCE)
6144 return 0;
6145
6146 return SD_BALANCE_EXEC | SD_BALANCE_FORK | SD_WAKE_AFFINE;
6147 }
6148
6149 static struct sched_domain *
6150 sd_numa_init(struct sched_domain_topology_level *tl, int cpu)
6151 {
6152 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6153 int level = tl->numa_level;
6154 int sd_weight = cpumask_weight(
6155 sched_domains_numa_masks[level][cpu_to_node(cpu)]);
6156
6157 *sd = (struct sched_domain){
6158 .min_interval = sd_weight,
6159 .max_interval = 2*sd_weight,
6160 .busy_factor = 32,
6161 .imbalance_pct = 125,
6162 .cache_nice_tries = 2,
6163 .busy_idx = 3,
6164 .idle_idx = 2,
6165 .newidle_idx = 0,
6166 .wake_idx = 0,
6167 .forkexec_idx = 0,
6168
6169 .flags = 1*SD_LOAD_BALANCE
6170 | 1*SD_BALANCE_NEWIDLE
6171 | 0*SD_BALANCE_EXEC
6172 | 0*SD_BALANCE_FORK
6173 | 0*SD_BALANCE_WAKE
6174 | 0*SD_WAKE_AFFINE
6175 | 0*SD_SHARE_CPUPOWER
6176 | 0*SD_SHARE_PKG_RESOURCES
6177 | 1*SD_SERIALIZE
6178 | 0*SD_PREFER_SIBLING
6179 | sd_local_flags(level)
6180 ,
6181 .last_balance = jiffies,
6182 .balance_interval = sd_weight,
6183 };
6184 SD_INIT_NAME(sd, NUMA);
6185 sd->private = &tl->data;
6186
6187 /*
6188 * Ugly hack to pass state to sd_numa_mask()...
6189 */
6190 sched_domains_curr_level = tl->numa_level;
6191
6192 return sd;
6193 }
6194
6195 static const struct cpumask *sd_numa_mask(int cpu)
6196 {
6197 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6198 }
6199
6200 static void sched_numa_warn(const char *str)
6201 {
6202 static int done = false;
6203 int i,j;
6204
6205 if (done)
6206 return;
6207
6208 done = true;
6209
6210 printk(KERN_WARNING "ERROR: %s\n\n", str);
6211
6212 for (i = 0; i < nr_node_ids; i++) {
6213 printk(KERN_WARNING " ");
6214 for (j = 0; j < nr_node_ids; j++)
6215 printk(KERN_CONT "%02d ", node_distance(i,j));
6216 printk(KERN_CONT "\n");
6217 }
6218 printk(KERN_WARNING "\n");
6219 }
6220
6221 static bool find_numa_distance(int distance)
6222 {
6223 int i;
6224
6225 if (distance == node_distance(0, 0))
6226 return true;
6227
6228 for (i = 0; i < sched_domains_numa_levels; i++) {
6229 if (sched_domains_numa_distance[i] == distance)
6230 return true;
6231 }
6232
6233 return false;
6234 }
6235
6236 static void sched_init_numa(void)
6237 {
6238 int next_distance, curr_distance = node_distance(0, 0);
6239 struct sched_domain_topology_level *tl;
6240 int level = 0;
6241 int i, j, k;
6242
6243 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6244 if (!sched_domains_numa_distance)
6245 return;
6246
6247 /*
6248 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6249 * unique distances in the node_distance() table.
6250 *
6251 * Assumes node_distance(0,j) includes all distances in
6252 * node_distance(i,j) in order to avoid cubic time.
6253 */
6254 next_distance = curr_distance;
6255 for (i = 0; i < nr_node_ids; i++) {
6256 for (j = 0; j < nr_node_ids; j++) {
6257 for (k = 0; k < nr_node_ids; k++) {
6258 int distance = node_distance(i, k);
6259
6260 if (distance > curr_distance &&
6261 (distance < next_distance ||
6262 next_distance == curr_distance))
6263 next_distance = distance;
6264
6265 /*
6266 * While not a strong assumption it would be nice to know
6267 * about cases where if node A is connected to B, B is not
6268 * equally connected to A.
6269 */
6270 if (sched_debug() && node_distance(k, i) != distance)
6271 sched_numa_warn("Node-distance not symmetric");
6272
6273 if (sched_debug() && i && !find_numa_distance(distance))
6274 sched_numa_warn("Node-0 not representative");
6275 }
6276 if (next_distance != curr_distance) {
6277 sched_domains_numa_distance[level++] = next_distance;
6278 sched_domains_numa_levels = level;
6279 curr_distance = next_distance;
6280 } else break;
6281 }
6282
6283 /*
6284 * In case of sched_debug() we verify the above assumption.
6285 */
6286 if (!sched_debug())
6287 break;
6288 }
6289 /*
6290 * 'level' contains the number of unique distances, excluding the
6291 * identity distance node_distance(i,i).
6292 *
6293 * The sched_domains_nume_distance[] array includes the actual distance
6294 * numbers.
6295 */
6296
6297 /*
6298 * Here, we should temporarily reset sched_domains_numa_levels to 0.
6299 * If it fails to allocate memory for array sched_domains_numa_masks[][],
6300 * the array will contain less then 'level' members. This could be
6301 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6302 * in other functions.
6303 *
6304 * We reset it to 'level' at the end of this function.
6305 */
6306 sched_domains_numa_levels = 0;
6307
6308 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6309 if (!sched_domains_numa_masks)
6310 return;
6311
6312 /*
6313 * Now for each level, construct a mask per node which contains all
6314 * cpus of nodes that are that many hops away from us.
6315 */
6316 for (i = 0; i < level; i++) {
6317 sched_domains_numa_masks[i] =
6318 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6319 if (!sched_domains_numa_masks[i])
6320 return;
6321
6322 for (j = 0; j < nr_node_ids; j++) {
6323 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
6324 if (!mask)
6325 return;
6326
6327 sched_domains_numa_masks[i][j] = mask;
6328
6329 for (k = 0; k < nr_node_ids; k++) {
6330 if (node_distance(j, k) > sched_domains_numa_distance[i])
6331 continue;
6332
6333 cpumask_or(mask, mask, cpumask_of_node(k));
6334 }
6335 }
6336 }
6337
6338 tl = kzalloc((ARRAY_SIZE(default_topology) + level) *
6339 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6340 if (!tl)
6341 return;
6342
6343 /*
6344 * Copy the default topology bits..
6345 */
6346 for (i = 0; default_topology[i].init; i++)
6347 tl[i] = default_topology[i];
6348
6349 /*
6350 * .. and append 'j' levels of NUMA goodness.
6351 */
6352 for (j = 0; j < level; i++, j++) {
6353 tl[i] = (struct sched_domain_topology_level){
6354 .init = sd_numa_init,
6355 .mask = sd_numa_mask,
6356 .flags = SDTL_OVERLAP,
6357 .numa_level = j,
6358 };
6359 }
6360
6361 sched_domain_topology = tl;
6362
6363 sched_domains_numa_levels = level;
6364 }
6365
6366 static void sched_domains_numa_masks_set(int cpu)
6367 {
6368 int i, j;
6369 int node = cpu_to_node(cpu);
6370
6371 for (i = 0; i < sched_domains_numa_levels; i++) {
6372 for (j = 0; j < nr_node_ids; j++) {
6373 if (node_distance(j, node) <= sched_domains_numa_distance[i])
6374 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6375 }
6376 }
6377 }
6378
6379 static void sched_domains_numa_masks_clear(int cpu)
6380 {
6381 int i, j;
6382 for (i = 0; i < sched_domains_numa_levels; i++) {
6383 for (j = 0; j < nr_node_ids; j++)
6384 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6385 }
6386 }
6387
6388 /*
6389 * Update sched_domains_numa_masks[level][node] array when new cpus
6390 * are onlined.
6391 */
6392 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6393 unsigned long action,
6394 void *hcpu)
6395 {
6396 int cpu = (long)hcpu;
6397
6398 switch (action & ~CPU_TASKS_FROZEN) {
6399 case CPU_ONLINE:
6400 sched_domains_numa_masks_set(cpu);
6401 break;
6402
6403 case CPU_DEAD:
6404 sched_domains_numa_masks_clear(cpu);
6405 break;
6406
6407 default:
6408 return NOTIFY_DONE;
6409 }
6410
6411 return NOTIFY_OK;
6412 }
6413 #else
6414 static inline void sched_init_numa(void)
6415 {
6416 }
6417
6418 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6419 unsigned long action,
6420 void *hcpu)
6421 {
6422 return 0;
6423 }
6424 #endif /* CONFIG_NUMA */
6425
6426 static int __sdt_alloc(const struct cpumask *cpu_map)
6427 {
6428 struct sched_domain_topology_level *tl;
6429 int j;
6430
6431 for (tl = sched_domain_topology; tl->init; tl++) {
6432 struct sd_data *sdd = &tl->data;
6433
6434 sdd->sd = alloc_percpu(struct sched_domain *);
6435 if (!sdd->sd)
6436 return -ENOMEM;
6437
6438 sdd->sg = alloc_percpu(struct sched_group *);
6439 if (!sdd->sg)
6440 return -ENOMEM;
6441
6442 sdd->sgp = alloc_percpu(struct sched_group_power *);
6443 if (!sdd->sgp)
6444 return -ENOMEM;
6445
6446 for_each_cpu(j, cpu_map) {
6447 struct sched_domain *sd;
6448 struct sched_group *sg;
6449 struct sched_group_power *sgp;
6450
6451 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6452 GFP_KERNEL, cpu_to_node(j));
6453 if (!sd)
6454 return -ENOMEM;
6455
6456 *per_cpu_ptr(sdd->sd, j) = sd;
6457
6458 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6459 GFP_KERNEL, cpu_to_node(j));
6460 if (!sg)
6461 return -ENOMEM;
6462
6463 sg->next = sg;
6464
6465 *per_cpu_ptr(sdd->sg, j) = sg;
6466
6467 sgp = kzalloc_node(sizeof(struct sched_group_power) + cpumask_size(),
6468 GFP_KERNEL, cpu_to_node(j));
6469 if (!sgp)
6470 return -ENOMEM;
6471
6472 *per_cpu_ptr(sdd->sgp, j) = sgp;
6473 }
6474 }
6475
6476 return 0;
6477 }
6478
6479 static void __sdt_free(const struct cpumask *cpu_map)
6480 {
6481 struct sched_domain_topology_level *tl;
6482 int j;
6483
6484 for (tl = sched_domain_topology; tl->init; tl++) {
6485 struct sd_data *sdd = &tl->data;
6486
6487 for_each_cpu(j, cpu_map) {
6488 struct sched_domain *sd;
6489
6490 if (sdd->sd) {
6491 sd = *per_cpu_ptr(sdd->sd, j);
6492 if (sd && (sd->flags & SD_OVERLAP))
6493 free_sched_groups(sd->groups, 0);
6494 kfree(*per_cpu_ptr(sdd->sd, j));
6495 }
6496
6497 if (sdd->sg)
6498 kfree(*per_cpu_ptr(sdd->sg, j));
6499 if (sdd->sgp)
6500 kfree(*per_cpu_ptr(sdd->sgp, j));
6501 }
6502 free_percpu(sdd->sd);
6503 sdd->sd = NULL;
6504 free_percpu(sdd->sg);
6505 sdd->sg = NULL;
6506 free_percpu(sdd->sgp);
6507 sdd->sgp = NULL;
6508 }
6509 }
6510
6511 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6512 struct s_data *d, const struct cpumask *cpu_map,
6513 struct sched_domain_attr *attr, struct sched_domain *child,
6514 int cpu)
6515 {
6516 struct sched_domain *sd = tl->init(tl, cpu);
6517 if (!sd)
6518 return child;
6519
6520 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6521 if (child) {
6522 sd->level = child->level + 1;
6523 sched_domain_level_max = max(sched_domain_level_max, sd->level);
6524 child->parent = sd;
6525 }
6526 sd->child = child;
6527 set_domain_attribute(sd, attr);
6528
6529 return sd;
6530 }
6531
6532 /*
6533 * Build sched domains for a given set of cpus and attach the sched domains
6534 * to the individual cpus
6535 */
6536 static int build_sched_domains(const struct cpumask *cpu_map,
6537 struct sched_domain_attr *attr)
6538 {
6539 enum s_alloc alloc_state = sa_none;
6540 struct sched_domain *sd;
6541 struct s_data d;
6542 int i, ret = -ENOMEM;
6543
6544 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
6545 if (alloc_state != sa_rootdomain)
6546 goto error;
6547
6548 /* Set up domains for cpus specified by the cpu_map. */
6549 for_each_cpu(i, cpu_map) {
6550 struct sched_domain_topology_level *tl;
6551
6552 sd = NULL;
6553 for (tl = sched_domain_topology; tl->init; tl++) {
6554 sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i);
6555 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
6556 sd->flags |= SD_OVERLAP;
6557 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
6558 break;
6559 }
6560
6561 while (sd->child)
6562 sd = sd->child;
6563
6564 *per_cpu_ptr(d.sd, i) = sd;
6565 }
6566
6567 /* Build the groups for the domains */
6568 for_each_cpu(i, cpu_map) {
6569 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6570 sd->span_weight = cpumask_weight(sched_domain_span(sd));
6571 if (sd->flags & SD_OVERLAP) {
6572 if (build_overlap_sched_groups(sd, i))
6573 goto error;
6574 } else {
6575 if (build_sched_groups(sd, i))
6576 goto error;
6577 }
6578 }
6579 }
6580
6581 /* Calculate CPU power for physical packages and nodes */
6582 for (i = nr_cpumask_bits-1; i >= 0; i--) {
6583 if (!cpumask_test_cpu(i, cpu_map))
6584 continue;
6585
6586 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6587 claim_allocations(i, sd);
6588 init_sched_groups_power(i, sd);
6589 }
6590 }
6591
6592 /* Attach the domains */
6593 rcu_read_lock();
6594 for_each_cpu(i, cpu_map) {
6595 sd = *per_cpu_ptr(d.sd, i);
6596 cpu_attach_domain(sd, d.rd, i);
6597 }
6598 rcu_read_unlock();
6599
6600 ret = 0;
6601 error:
6602 __free_domain_allocs(&d, alloc_state, cpu_map);
6603 return ret;
6604 }
6605
6606 static cpumask_var_t *doms_cur; /* current sched domains */
6607 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
6608 static struct sched_domain_attr *dattr_cur;
6609 /* attribues of custom domains in 'doms_cur' */
6610
6611 /*
6612 * Special case: If a kmalloc of a doms_cur partition (array of
6613 * cpumask) fails, then fallback to a single sched domain,
6614 * as determined by the single cpumask fallback_doms.
6615 */
6616 static cpumask_var_t fallback_doms;
6617
6618 /*
6619 * arch_update_cpu_topology lets virtualized architectures update the
6620 * cpu core maps. It is supposed to return 1 if the topology changed
6621 * or 0 if it stayed the same.
6622 */
6623 int __attribute__((weak)) arch_update_cpu_topology(void)
6624 {
6625 return 0;
6626 }
6627
6628 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
6629 {
6630 int i;
6631 cpumask_var_t *doms;
6632
6633 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
6634 if (!doms)
6635 return NULL;
6636 for (i = 0; i < ndoms; i++) {
6637 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
6638 free_sched_domains(doms, i);
6639 return NULL;
6640 }
6641 }
6642 return doms;
6643 }
6644
6645 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
6646 {
6647 unsigned int i;
6648 for (i = 0; i < ndoms; i++)
6649 free_cpumask_var(doms[i]);
6650 kfree(doms);
6651 }
6652
6653 /*
6654 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6655 * For now this just excludes isolated cpus, but could be used to
6656 * exclude other special cases in the future.
6657 */
6658 static int init_sched_domains(const struct cpumask *cpu_map)
6659 {
6660 int err;
6661
6662 arch_update_cpu_topology();
6663 ndoms_cur = 1;
6664 doms_cur = alloc_sched_domains(ndoms_cur);
6665 if (!doms_cur)
6666 doms_cur = &fallback_doms;
6667 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
6668 err = build_sched_domains(doms_cur[0], NULL);
6669 register_sched_domain_sysctl();
6670
6671 return err;
6672 }
6673
6674 /*
6675 * Detach sched domains from a group of cpus specified in cpu_map
6676 * These cpus will now be attached to the NULL domain
6677 */
6678 static void detach_destroy_domains(const struct cpumask *cpu_map)
6679 {
6680 int i;
6681
6682 rcu_read_lock();
6683 for_each_cpu(i, cpu_map)
6684 cpu_attach_domain(NULL, &def_root_domain, i);
6685 rcu_read_unlock();
6686 }
6687
6688 /* handle null as "default" */
6689 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
6690 struct sched_domain_attr *new, int idx_new)
6691 {
6692 struct sched_domain_attr tmp;
6693
6694 /* fast path */
6695 if (!new && !cur)
6696 return 1;
6697
6698 tmp = SD_ATTR_INIT;
6699 return !memcmp(cur ? (cur + idx_cur) : &tmp,
6700 new ? (new + idx_new) : &tmp,
6701 sizeof(struct sched_domain_attr));
6702 }
6703
6704 /*
6705 * Partition sched domains as specified by the 'ndoms_new'
6706 * cpumasks in the array doms_new[] of cpumasks. This compares
6707 * doms_new[] to the current sched domain partitioning, doms_cur[].
6708 * It destroys each deleted domain and builds each new domain.
6709 *
6710 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
6711 * The masks don't intersect (don't overlap.) We should setup one
6712 * sched domain for each mask. CPUs not in any of the cpumasks will
6713 * not be load balanced. If the same cpumask appears both in the
6714 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6715 * it as it is.
6716 *
6717 * The passed in 'doms_new' should be allocated using
6718 * alloc_sched_domains. This routine takes ownership of it and will
6719 * free_sched_domains it when done with it. If the caller failed the
6720 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
6721 * and partition_sched_domains() will fallback to the single partition
6722 * 'fallback_doms', it also forces the domains to be rebuilt.
6723 *
6724 * If doms_new == NULL it will be replaced with cpu_online_mask.
6725 * ndoms_new == 0 is a special case for destroying existing domains,
6726 * and it will not create the default domain.
6727 *
6728 * Call with hotplug lock held
6729 */
6730 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
6731 struct sched_domain_attr *dattr_new)
6732 {
6733 int i, j, n;
6734 int new_topology;
6735
6736 mutex_lock(&sched_domains_mutex);
6737
6738 /* always unregister in case we don't destroy any domains */
6739 unregister_sched_domain_sysctl();
6740
6741 /* Let architecture update cpu core mappings. */
6742 new_topology = arch_update_cpu_topology();
6743
6744 n = doms_new ? ndoms_new : 0;
6745
6746 /* Destroy deleted domains */
6747 for (i = 0; i < ndoms_cur; i++) {
6748 for (j = 0; j < n && !new_topology; j++) {
6749 if (cpumask_equal(doms_cur[i], doms_new[j])
6750 && dattrs_equal(dattr_cur, i, dattr_new, j))
6751 goto match1;
6752 }
6753 /* no match - a current sched domain not in new doms_new[] */
6754 detach_destroy_domains(doms_cur[i]);
6755 match1:
6756 ;
6757 }
6758
6759 if (doms_new == NULL) {
6760 ndoms_cur = 0;
6761 doms_new = &fallback_doms;
6762 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
6763 WARN_ON_ONCE(dattr_new);
6764 }
6765
6766 /* Build new domains */
6767 for (i = 0; i < ndoms_new; i++) {
6768 for (j = 0; j < ndoms_cur && !new_topology; j++) {
6769 if (cpumask_equal(doms_new[i], doms_cur[j])
6770 && dattrs_equal(dattr_new, i, dattr_cur, j))
6771 goto match2;
6772 }
6773 /* no match - add a new doms_new */
6774 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
6775 match2:
6776 ;
6777 }
6778
6779 /* Remember the new sched domains */
6780 if (doms_cur != &fallback_doms)
6781 free_sched_domains(doms_cur, ndoms_cur);
6782 kfree(dattr_cur); /* kfree(NULL) is safe */
6783 doms_cur = doms_new;
6784 dattr_cur = dattr_new;
6785 ndoms_cur = ndoms_new;
6786
6787 register_sched_domain_sysctl();
6788
6789 mutex_unlock(&sched_domains_mutex);
6790 }
6791
6792 static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
6793
6794 /*
6795 * Update cpusets according to cpu_active mask. If cpusets are
6796 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
6797 * around partition_sched_domains().
6798 *
6799 * If we come here as part of a suspend/resume, don't touch cpusets because we
6800 * want to restore it back to its original state upon resume anyway.
6801 */
6802 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
6803 void *hcpu)
6804 {
6805 switch (action) {
6806 case CPU_ONLINE_FROZEN:
6807 case CPU_DOWN_FAILED_FROZEN:
6808
6809 /*
6810 * num_cpus_frozen tracks how many CPUs are involved in suspend
6811 * resume sequence. As long as this is not the last online
6812 * operation in the resume sequence, just build a single sched
6813 * domain, ignoring cpusets.
6814 */
6815 num_cpus_frozen--;
6816 if (likely(num_cpus_frozen)) {
6817 partition_sched_domains(1, NULL, NULL);
6818 break;
6819 }
6820
6821 /*
6822 * This is the last CPU online operation. So fall through and
6823 * restore the original sched domains by considering the
6824 * cpuset configurations.
6825 */
6826
6827 case CPU_ONLINE:
6828 case CPU_DOWN_FAILED:
6829 cpuset_update_active_cpus(true);
6830 break;
6831 default:
6832 return NOTIFY_DONE;
6833 }
6834 return NOTIFY_OK;
6835 }
6836
6837 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
6838 void *hcpu)
6839 {
6840 switch (action) {
6841 case CPU_DOWN_PREPARE:
6842 cpuset_update_active_cpus(false);
6843 break;
6844 case CPU_DOWN_PREPARE_FROZEN:
6845 num_cpus_frozen++;
6846 partition_sched_domains(1, NULL, NULL);
6847 break;
6848 default:
6849 return NOTIFY_DONE;
6850 }
6851 return NOTIFY_OK;
6852 }
6853
6854 void __init sched_init_smp(void)
6855 {
6856 cpumask_var_t non_isolated_cpus;
6857
6858 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
6859 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
6860
6861 sched_init_numa();
6862
6863 get_online_cpus();
6864 mutex_lock(&sched_domains_mutex);
6865 init_sched_domains(cpu_active_mask);
6866 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
6867 if (cpumask_empty(non_isolated_cpus))
6868 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
6869 mutex_unlock(&sched_domains_mutex);
6870 put_online_cpus();
6871
6872 hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
6873 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
6874 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
6875
6876 /* RT runtime code needs to handle some hotplug events */
6877 hotcpu_notifier(update_runtime, 0);
6878
6879 init_hrtick();
6880
6881 /* Move init over to a non-isolated CPU */
6882 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
6883 BUG();
6884 sched_init_granularity();
6885 free_cpumask_var(non_isolated_cpus);
6886
6887 init_sched_rt_class();
6888 }
6889 #else
6890 void __init sched_init_smp(void)
6891 {
6892 sched_init_granularity();
6893 }
6894 #endif /* CONFIG_SMP */
6895
6896 const_debug unsigned int sysctl_timer_migration = 1;
6897
6898 int in_sched_functions(unsigned long addr)
6899 {
6900 return in_lock_functions(addr) ||
6901 (addr >= (unsigned long)__sched_text_start
6902 && addr < (unsigned long)__sched_text_end);
6903 }
6904
6905 #ifdef CONFIG_CGROUP_SCHED
6906 /*
6907 * Default task group.
6908 * Every task in system belongs to this group at bootup.
6909 */
6910 struct task_group root_task_group;
6911 LIST_HEAD(task_groups);
6912 #endif
6913
6914 DECLARE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
6915
6916 void __init sched_init(void)
6917 {
6918 int i, j;
6919 unsigned long alloc_size = 0, ptr;
6920
6921 #ifdef CONFIG_FAIR_GROUP_SCHED
6922 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
6923 #endif
6924 #ifdef CONFIG_RT_GROUP_SCHED
6925 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
6926 #endif
6927 #ifdef CONFIG_CPUMASK_OFFSTACK
6928 alloc_size += num_possible_cpus() * cpumask_size();
6929 #endif
6930 if (alloc_size) {
6931 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
6932
6933 #ifdef CONFIG_FAIR_GROUP_SCHED
6934 root_task_group.se = (struct sched_entity **)ptr;
6935 ptr += nr_cpu_ids * sizeof(void **);
6936
6937 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
6938 ptr += nr_cpu_ids * sizeof(void **);
6939
6940 #endif /* CONFIG_FAIR_GROUP_SCHED */
6941 #ifdef CONFIG_RT_GROUP_SCHED
6942 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
6943 ptr += nr_cpu_ids * sizeof(void **);
6944
6945 root_task_group.rt_rq = (struct rt_rq **)ptr;
6946 ptr += nr_cpu_ids * sizeof(void **);
6947
6948 #endif /* CONFIG_RT_GROUP_SCHED */
6949 #ifdef CONFIG_CPUMASK_OFFSTACK
6950 for_each_possible_cpu(i) {
6951 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
6952 ptr += cpumask_size();
6953 }
6954 #endif /* CONFIG_CPUMASK_OFFSTACK */
6955 }
6956
6957 #ifdef CONFIG_SMP
6958 init_defrootdomain();
6959 #endif
6960
6961 init_rt_bandwidth(&def_rt_bandwidth,
6962 global_rt_period(), global_rt_runtime());
6963
6964 #ifdef CONFIG_RT_GROUP_SCHED
6965 init_rt_bandwidth(&root_task_group.rt_bandwidth,
6966 global_rt_period(), global_rt_runtime());
6967 #endif /* CONFIG_RT_GROUP_SCHED */
6968
6969 #ifdef CONFIG_CGROUP_SCHED
6970 list_add(&root_task_group.list, &task_groups);
6971 INIT_LIST_HEAD(&root_task_group.children);
6972 INIT_LIST_HEAD(&root_task_group.siblings);
6973 autogroup_init(&init_task);
6974
6975 #endif /* CONFIG_CGROUP_SCHED */
6976
6977 #ifdef CONFIG_CGROUP_CPUACCT
6978 root_cpuacct.cpustat = &kernel_cpustat;
6979 root_cpuacct.cpuusage = alloc_percpu(u64);
6980 /* Too early, not expected to fail */
6981 BUG_ON(!root_cpuacct.cpuusage);
6982 #endif
6983 for_each_possible_cpu(i) {
6984 struct rq *rq;
6985
6986 rq = cpu_rq(i);
6987 raw_spin_lock_init(&rq->lock);
6988 rq->nr_running = 0;
6989 rq->calc_load_active = 0;
6990 rq->calc_load_update = jiffies + LOAD_FREQ;
6991 init_cfs_rq(&rq->cfs);
6992 init_rt_rq(&rq->rt, rq);
6993 #ifdef CONFIG_FAIR_GROUP_SCHED
6994 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6995 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6996 /*
6997 * How much cpu bandwidth does root_task_group get?
6998 *
6999 * In case of task-groups formed thr' the cgroup filesystem, it
7000 * gets 100% of the cpu resources in the system. This overall
7001 * system cpu resource is divided among the tasks of
7002 * root_task_group and its child task-groups in a fair manner,
7003 * based on each entity's (task or task-group's) weight
7004 * (se->load.weight).
7005 *
7006 * In other words, if root_task_group has 10 tasks of weight
7007 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7008 * then A0's share of the cpu resource is:
7009 *
7010 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7011 *
7012 * We achieve this by letting root_task_group's tasks sit
7013 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7014 */
7015 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7016 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7017 #endif /* CONFIG_FAIR_GROUP_SCHED */
7018
7019 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7020 #ifdef CONFIG_RT_GROUP_SCHED
7021 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7022 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7023 #endif
7024
7025 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7026 rq->cpu_load[j] = 0;
7027
7028 rq->last_load_update_tick = jiffies;
7029
7030 #ifdef CONFIG_SMP
7031 rq->sd = NULL;
7032 rq->rd = NULL;
7033 rq->cpu_power = SCHED_POWER_SCALE;
7034 rq->post_schedule = 0;
7035 rq->active_balance = 0;
7036 rq->next_balance = jiffies;
7037 rq->push_cpu = 0;
7038 rq->cpu = i;
7039 rq->online = 0;
7040 rq->idle_stamp = 0;
7041 rq->avg_idle = 2*sysctl_sched_migration_cost;
7042
7043 INIT_LIST_HEAD(&rq->cfs_tasks);
7044
7045 rq_attach_root(rq, &def_root_domain);
7046 #ifdef CONFIG_NO_HZ_COMMON
7047 rq->nohz_flags = 0;
7048 #endif
7049 #endif
7050 init_rq_hrtick(rq);
7051 atomic_set(&rq->nr_iowait, 0);
7052 }
7053
7054 set_load_weight(&init_task);
7055
7056 #ifdef CONFIG_PREEMPT_NOTIFIERS
7057 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7058 #endif
7059
7060 #ifdef CONFIG_RT_MUTEXES
7061 plist_head_init(&init_task.pi_waiters);
7062 #endif
7063
7064 /*
7065 * The boot idle thread does lazy MMU switching as well:
7066 */
7067 atomic_inc(&init_mm.mm_count);
7068 enter_lazy_tlb(&init_mm, current);
7069
7070 /*
7071 * Make us the idle thread. Technically, schedule() should not be
7072 * called from this thread, however somewhere below it might be,
7073 * but because we are the idle thread, we just pick up running again
7074 * when this runqueue becomes "idle".
7075 */
7076 init_idle(current, smp_processor_id());
7077
7078 calc_load_update = jiffies + LOAD_FREQ;
7079
7080 /*
7081 * During early bootup we pretend to be a normal task:
7082 */
7083 current->sched_class = &fair_sched_class;
7084
7085 #ifdef CONFIG_SMP
7086 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7087 /* May be allocated at isolcpus cmdline parse time */
7088 if (cpu_isolated_map == NULL)
7089 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7090 idle_thread_set_boot_cpu();
7091 #endif
7092 init_sched_fair_class();
7093
7094 scheduler_running = 1;
7095 }
7096
7097 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7098 static inline int preempt_count_equals(int preempt_offset)
7099 {
7100 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
7101
7102 return (nested == preempt_offset);
7103 }
7104
7105 void __might_sleep(const char *file, int line, int preempt_offset)
7106 {
7107 static unsigned long prev_jiffy; /* ratelimiting */
7108
7109 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7110 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
7111 system_state != SYSTEM_RUNNING || oops_in_progress)
7112 return;
7113 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7114 return;
7115 prev_jiffy = jiffies;
7116
7117 printk(KERN_ERR
7118 "BUG: sleeping function called from invalid context at %s:%d\n",
7119 file, line);
7120 printk(KERN_ERR
7121 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7122 in_atomic(), irqs_disabled(),
7123 current->pid, current->comm);
7124
7125 debug_show_held_locks(current);
7126 if (irqs_disabled())
7127 print_irqtrace_events(current);
7128 dump_stack();
7129 }
7130 EXPORT_SYMBOL(__might_sleep);
7131 #endif
7132
7133 #ifdef CONFIG_MAGIC_SYSRQ
7134 static void normalize_task(struct rq *rq, struct task_struct *p)
7135 {
7136 const struct sched_class *prev_class = p->sched_class;
7137 int old_prio = p->prio;
7138 int on_rq;
7139
7140 on_rq = p->on_rq;
7141 if (on_rq)
7142 dequeue_task(rq, p, 0);
7143 __setscheduler(rq, p, SCHED_NORMAL, 0);
7144 if (on_rq) {
7145 enqueue_task(rq, p, 0);
7146 resched_task(rq->curr);
7147 }
7148
7149 check_class_changed(rq, p, prev_class, old_prio);
7150 }
7151
7152 void normalize_rt_tasks(void)
7153 {
7154 struct task_struct *g, *p;
7155 unsigned long flags;
7156 struct rq *rq;
7157
7158 read_lock_irqsave(&tasklist_lock, flags);
7159 do_each_thread(g, p) {
7160 /*
7161 * Only normalize user tasks:
7162 */
7163 if (!p->mm)
7164 continue;
7165
7166 p->se.exec_start = 0;
7167 #ifdef CONFIG_SCHEDSTATS
7168 p->se.statistics.wait_start = 0;
7169 p->se.statistics.sleep_start = 0;
7170 p->se.statistics.block_start = 0;
7171 #endif
7172
7173 if (!rt_task(p)) {
7174 /*
7175 * Renice negative nice level userspace
7176 * tasks back to 0:
7177 */
7178 if (TASK_NICE(p) < 0 && p->mm)
7179 set_user_nice(p, 0);
7180 continue;
7181 }
7182
7183 raw_spin_lock(&p->pi_lock);
7184 rq = __task_rq_lock(p);
7185
7186 normalize_task(rq, p);
7187
7188 __task_rq_unlock(rq);
7189 raw_spin_unlock(&p->pi_lock);
7190 } while_each_thread(g, p);
7191
7192 read_unlock_irqrestore(&tasklist_lock, flags);
7193 }
7194
7195 #endif /* CONFIG_MAGIC_SYSRQ */
7196
7197 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7198 /*
7199 * These functions are only useful for the IA64 MCA handling, or kdb.
7200 *
7201 * They can only be called when the whole system has been
7202 * stopped - every CPU needs to be quiescent, and no scheduling
7203 * activity can take place. Using them for anything else would
7204 * be a serious bug, and as a result, they aren't even visible
7205 * under any other configuration.
7206 */
7207
7208 /**
7209 * curr_task - return the current task for a given cpu.
7210 * @cpu: the processor in question.
7211 *
7212 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7213 */
7214 struct task_struct *curr_task(int cpu)
7215 {
7216 return cpu_curr(cpu);
7217 }
7218
7219 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7220
7221 #ifdef CONFIG_IA64
7222 /**
7223 * set_curr_task - set the current task for a given cpu.
7224 * @cpu: the processor in question.
7225 * @p: the task pointer to set.
7226 *
7227 * Description: This function must only be used when non-maskable interrupts
7228 * are serviced on a separate stack. It allows the architecture to switch the
7229 * notion of the current task on a cpu in a non-blocking manner. This function
7230 * must be called with all CPU's synchronized, and interrupts disabled, the
7231 * and caller must save the original value of the current task (see
7232 * curr_task() above) and restore that value before reenabling interrupts and
7233 * re-starting the system.
7234 *
7235 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7236 */
7237 void set_curr_task(int cpu, struct task_struct *p)
7238 {
7239 cpu_curr(cpu) = p;
7240 }
7241
7242 #endif
7243
7244 #ifdef CONFIG_CGROUP_SCHED
7245 /* task_group_lock serializes the addition/removal of task groups */
7246 static DEFINE_SPINLOCK(task_group_lock);
7247
7248 static void free_sched_group(struct task_group *tg)
7249 {
7250 free_fair_sched_group(tg);
7251 free_rt_sched_group(tg);
7252 autogroup_free(tg);
7253 kfree(tg);
7254 }
7255
7256 /* allocate runqueue etc for a new task group */
7257 struct task_group *sched_create_group(struct task_group *parent)
7258 {
7259 struct task_group *tg;
7260
7261 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7262 if (!tg)
7263 return ERR_PTR(-ENOMEM);
7264
7265 if (!alloc_fair_sched_group(tg, parent))
7266 goto err;
7267
7268 if (!alloc_rt_sched_group(tg, parent))
7269 goto err;
7270
7271 return tg;
7272
7273 err:
7274 free_sched_group(tg);
7275 return ERR_PTR(-ENOMEM);
7276 }
7277
7278 void sched_online_group(struct task_group *tg, struct task_group *parent)
7279 {
7280 unsigned long flags;
7281
7282 spin_lock_irqsave(&task_group_lock, flags);
7283 list_add_rcu(&tg->list, &task_groups);
7284
7285 WARN_ON(!parent); /* root should already exist */
7286
7287 tg->parent = parent;
7288 INIT_LIST_HEAD(&tg->children);
7289 list_add_rcu(&tg->siblings, &parent->children);
7290 spin_unlock_irqrestore(&task_group_lock, flags);
7291 }
7292
7293 /* rcu callback to free various structures associated with a task group */
7294 static void free_sched_group_rcu(struct rcu_head *rhp)
7295 {
7296 /* now it should be safe to free those cfs_rqs */
7297 free_sched_group(container_of(rhp, struct task_group, rcu));
7298 }
7299
7300 /* Destroy runqueue etc associated with a task group */
7301 void sched_destroy_group(struct task_group *tg)
7302 {
7303 /* wait for possible concurrent references to cfs_rqs complete */
7304 call_rcu(&tg->rcu, free_sched_group_rcu);
7305 }
7306
7307 void sched_offline_group(struct task_group *tg)
7308 {
7309 unsigned long flags;
7310 int i;
7311
7312 /* end participation in shares distribution */
7313 for_each_possible_cpu(i)
7314 unregister_fair_sched_group(tg, i);
7315
7316 spin_lock_irqsave(&task_group_lock, flags);
7317 list_del_rcu(&tg->list);
7318 list_del_rcu(&tg->siblings);
7319 spin_unlock_irqrestore(&task_group_lock, flags);
7320 }
7321
7322 /* change task's runqueue when it moves between groups.
7323 * The caller of this function should have put the task in its new group
7324 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7325 * reflect its new group.
7326 */
7327 void sched_move_task(struct task_struct *tsk)
7328 {
7329 struct task_group *tg;
7330 int on_rq, running;
7331 unsigned long flags;
7332 struct rq *rq;
7333
7334 rq = task_rq_lock(tsk, &flags);
7335
7336 running = task_current(rq, tsk);
7337 on_rq = tsk->on_rq;
7338
7339 if (on_rq)
7340 dequeue_task(rq, tsk, 0);
7341 if (unlikely(running))
7342 tsk->sched_class->put_prev_task(rq, tsk);
7343
7344 tg = container_of(task_subsys_state_check(tsk, cpu_cgroup_subsys_id,
7345 lockdep_is_held(&tsk->sighand->siglock)),
7346 struct task_group, css);
7347 tg = autogroup_task_group(tsk, tg);
7348 tsk->sched_task_group = tg;
7349
7350 #ifdef CONFIG_FAIR_GROUP_SCHED
7351 if (tsk->sched_class->task_move_group)
7352 tsk->sched_class->task_move_group(tsk, on_rq);
7353 else
7354 #endif
7355 set_task_rq(tsk, task_cpu(tsk));
7356
7357 if (unlikely(running))
7358 tsk->sched_class->set_curr_task(rq);
7359 if (on_rq)
7360 enqueue_task(rq, tsk, 0);
7361
7362 task_rq_unlock(rq, tsk, &flags);
7363 }
7364 #endif /* CONFIG_CGROUP_SCHED */
7365
7366 #if defined(CONFIG_RT_GROUP_SCHED) || defined(CONFIG_CFS_BANDWIDTH)
7367 static unsigned long to_ratio(u64 period, u64 runtime)
7368 {
7369 if (runtime == RUNTIME_INF)
7370 return 1ULL << 20;
7371
7372 return div64_u64(runtime << 20, period);
7373 }
7374 #endif
7375
7376 #ifdef CONFIG_RT_GROUP_SCHED
7377 /*
7378 * Ensure that the real time constraints are schedulable.
7379 */
7380 static DEFINE_MUTEX(rt_constraints_mutex);
7381
7382 /* Must be called with tasklist_lock held */
7383 static inline int tg_has_rt_tasks(struct task_group *tg)
7384 {
7385 struct task_struct *g, *p;
7386
7387 do_each_thread(g, p) {
7388 if (rt_task(p) && task_rq(p)->rt.tg == tg)
7389 return 1;
7390 } while_each_thread(g, p);
7391
7392 return 0;
7393 }
7394
7395 struct rt_schedulable_data {
7396 struct task_group *tg;
7397 u64 rt_period;
7398 u64 rt_runtime;
7399 };
7400
7401 static int tg_rt_schedulable(struct task_group *tg, void *data)
7402 {
7403 struct rt_schedulable_data *d = data;
7404 struct task_group *child;
7405 unsigned long total, sum = 0;
7406 u64 period, runtime;
7407
7408 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7409 runtime = tg->rt_bandwidth.rt_runtime;
7410
7411 if (tg == d->tg) {
7412 period = d->rt_period;
7413 runtime = d->rt_runtime;
7414 }
7415
7416 /*
7417 * Cannot have more runtime than the period.
7418 */
7419 if (runtime > period && runtime != RUNTIME_INF)
7420 return -EINVAL;
7421
7422 /*
7423 * Ensure we don't starve existing RT tasks.
7424 */
7425 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7426 return -EBUSY;
7427
7428 total = to_ratio(period, runtime);
7429
7430 /*
7431 * Nobody can have more than the global setting allows.
7432 */
7433 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7434 return -EINVAL;
7435
7436 /*
7437 * The sum of our children's runtime should not exceed our own.
7438 */
7439 list_for_each_entry_rcu(child, &tg->children, siblings) {
7440 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7441 runtime = child->rt_bandwidth.rt_runtime;
7442
7443 if (child == d->tg) {
7444 period = d->rt_period;
7445 runtime = d->rt_runtime;
7446 }
7447
7448 sum += to_ratio(period, runtime);
7449 }
7450
7451 if (sum > total)
7452 return -EINVAL;
7453
7454 return 0;
7455 }
7456
7457 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7458 {
7459 int ret;
7460
7461 struct rt_schedulable_data data = {
7462 .tg = tg,
7463 .rt_period = period,
7464 .rt_runtime = runtime,
7465 };
7466
7467 rcu_read_lock();
7468 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
7469 rcu_read_unlock();
7470
7471 return ret;
7472 }
7473
7474 static int tg_set_rt_bandwidth(struct task_group *tg,
7475 u64 rt_period, u64 rt_runtime)
7476 {
7477 int i, err = 0;
7478
7479 mutex_lock(&rt_constraints_mutex);
7480 read_lock(&tasklist_lock);
7481 err = __rt_schedulable(tg, rt_period, rt_runtime);
7482 if (err)
7483 goto unlock;
7484
7485 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7486 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7487 tg->rt_bandwidth.rt_runtime = rt_runtime;
7488
7489 for_each_possible_cpu(i) {
7490 struct rt_rq *rt_rq = tg->rt_rq[i];
7491
7492 raw_spin_lock(&rt_rq->rt_runtime_lock);
7493 rt_rq->rt_runtime = rt_runtime;
7494 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7495 }
7496 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7497 unlock:
7498 read_unlock(&tasklist_lock);
7499 mutex_unlock(&rt_constraints_mutex);
7500
7501 return err;
7502 }
7503
7504 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
7505 {
7506 u64 rt_runtime, rt_period;
7507
7508 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7509 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7510 if (rt_runtime_us < 0)
7511 rt_runtime = RUNTIME_INF;
7512
7513 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7514 }
7515
7516 static long sched_group_rt_runtime(struct task_group *tg)
7517 {
7518 u64 rt_runtime_us;
7519
7520 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
7521 return -1;
7522
7523 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
7524 do_div(rt_runtime_us, NSEC_PER_USEC);
7525 return rt_runtime_us;
7526 }
7527
7528 static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
7529 {
7530 u64 rt_runtime, rt_period;
7531
7532 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
7533 rt_runtime = tg->rt_bandwidth.rt_runtime;
7534
7535 if (rt_period == 0)
7536 return -EINVAL;
7537
7538 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7539 }
7540
7541 static long sched_group_rt_period(struct task_group *tg)
7542 {
7543 u64 rt_period_us;
7544
7545 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
7546 do_div(rt_period_us, NSEC_PER_USEC);
7547 return rt_period_us;
7548 }
7549
7550 static int sched_rt_global_constraints(void)
7551 {
7552 u64 runtime, period;
7553 int ret = 0;
7554
7555 if (sysctl_sched_rt_period <= 0)
7556 return -EINVAL;
7557
7558 runtime = global_rt_runtime();
7559 period = global_rt_period();
7560
7561 /*
7562 * Sanity check on the sysctl variables.
7563 */
7564 if (runtime > period && runtime != RUNTIME_INF)
7565 return -EINVAL;
7566
7567 mutex_lock(&rt_constraints_mutex);
7568 read_lock(&tasklist_lock);
7569 ret = __rt_schedulable(NULL, 0, 0);
7570 read_unlock(&tasklist_lock);
7571 mutex_unlock(&rt_constraints_mutex);
7572
7573 return ret;
7574 }
7575
7576 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
7577 {
7578 /* Don't accept realtime tasks when there is no way for them to run */
7579 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
7580 return 0;
7581
7582 return 1;
7583 }
7584
7585 #else /* !CONFIG_RT_GROUP_SCHED */
7586 static int sched_rt_global_constraints(void)
7587 {
7588 unsigned long flags;
7589 int i;
7590
7591 if (sysctl_sched_rt_period <= 0)
7592 return -EINVAL;
7593
7594 /*
7595 * There's always some RT tasks in the root group
7596 * -- migration, kstopmachine etc..
7597 */
7598 if (sysctl_sched_rt_runtime == 0)
7599 return -EBUSY;
7600
7601 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
7602 for_each_possible_cpu(i) {
7603 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
7604
7605 raw_spin_lock(&rt_rq->rt_runtime_lock);
7606 rt_rq->rt_runtime = global_rt_runtime();
7607 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7608 }
7609 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
7610
7611 return 0;
7612 }
7613 #endif /* CONFIG_RT_GROUP_SCHED */
7614
7615 int sched_rr_handler(struct ctl_table *table, int write,
7616 void __user *buffer, size_t *lenp,
7617 loff_t *ppos)
7618 {
7619 int ret;
7620 static DEFINE_MUTEX(mutex);
7621
7622 mutex_lock(&mutex);
7623 ret = proc_dointvec(table, write, buffer, lenp, ppos);
7624 /* make sure that internally we keep jiffies */
7625 /* also, writing zero resets timeslice to default */
7626 if (!ret && write) {
7627 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
7628 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
7629 }
7630 mutex_unlock(&mutex);
7631 return ret;
7632 }
7633
7634 int sched_rt_handler(struct ctl_table *table, int write,
7635 void __user *buffer, size_t *lenp,
7636 loff_t *ppos)
7637 {
7638 int ret;
7639 int old_period, old_runtime;
7640 static DEFINE_MUTEX(mutex);
7641
7642 mutex_lock(&mutex);
7643 old_period = sysctl_sched_rt_period;
7644 old_runtime = sysctl_sched_rt_runtime;
7645
7646 ret = proc_dointvec(table, write, buffer, lenp, ppos);
7647
7648 if (!ret && write) {
7649 ret = sched_rt_global_constraints();
7650 if (ret) {
7651 sysctl_sched_rt_period = old_period;
7652 sysctl_sched_rt_runtime = old_runtime;
7653 } else {
7654 def_rt_bandwidth.rt_runtime = global_rt_runtime();
7655 def_rt_bandwidth.rt_period =
7656 ns_to_ktime(global_rt_period());
7657 }
7658 }
7659 mutex_unlock(&mutex);
7660
7661 return ret;
7662 }
7663
7664 #ifdef CONFIG_CGROUP_SCHED
7665
7666 /* return corresponding task_group object of a cgroup */
7667 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
7668 {
7669 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7670 struct task_group, css);
7671 }
7672
7673 static struct cgroup_subsys_state *cpu_cgroup_css_alloc(struct cgroup *cgrp)
7674 {
7675 struct task_group *tg, *parent;
7676
7677 if (!cgrp->parent) {
7678 /* This is early initialization for the top cgroup */
7679 return &root_task_group.css;
7680 }
7681
7682 parent = cgroup_tg(cgrp->parent);
7683 tg = sched_create_group(parent);
7684 if (IS_ERR(tg))
7685 return ERR_PTR(-ENOMEM);
7686
7687 return &tg->css;
7688 }
7689
7690 static int cpu_cgroup_css_online(struct cgroup *cgrp)
7691 {
7692 struct task_group *tg = cgroup_tg(cgrp);
7693 struct task_group *parent;
7694
7695 if (!cgrp->parent)
7696 return 0;
7697
7698 parent = cgroup_tg(cgrp->parent);
7699 sched_online_group(tg, parent);
7700 return 0;
7701 }
7702
7703 static void cpu_cgroup_css_free(struct cgroup *cgrp)
7704 {
7705 struct task_group *tg = cgroup_tg(cgrp);
7706
7707 sched_destroy_group(tg);
7708 }
7709
7710 static void cpu_cgroup_css_offline(struct cgroup *cgrp)
7711 {
7712 struct task_group *tg = cgroup_tg(cgrp);
7713
7714 sched_offline_group(tg);
7715 }
7716
7717 static int cpu_cgroup_can_attach(struct cgroup *cgrp,
7718 struct cgroup_taskset *tset)
7719 {
7720 struct task_struct *task;
7721
7722 cgroup_taskset_for_each(task, cgrp, tset) {
7723 #ifdef CONFIG_RT_GROUP_SCHED
7724 if (!sched_rt_can_attach(cgroup_tg(cgrp), task))
7725 return -EINVAL;
7726 #else
7727 /* We don't support RT-tasks being in separate groups */
7728 if (task->sched_class != &fair_sched_class)
7729 return -EINVAL;
7730 #endif
7731 }
7732 return 0;
7733 }
7734
7735 static void cpu_cgroup_attach(struct cgroup *cgrp,
7736 struct cgroup_taskset *tset)
7737 {
7738 struct task_struct *task;
7739
7740 cgroup_taskset_for_each(task, cgrp, tset)
7741 sched_move_task(task);
7742 }
7743
7744 static void
7745 cpu_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp,
7746 struct task_struct *task)
7747 {
7748 /*
7749 * cgroup_exit() is called in the copy_process() failure path.
7750 * Ignore this case since the task hasn't ran yet, this avoids
7751 * trying to poke a half freed task state from generic code.
7752 */
7753 if (!(task->flags & PF_EXITING))
7754 return;
7755
7756 sched_move_task(task);
7757 }
7758
7759 #ifdef CONFIG_FAIR_GROUP_SCHED
7760 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
7761 u64 shareval)
7762 {
7763 return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval));
7764 }
7765
7766 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
7767 {
7768 struct task_group *tg = cgroup_tg(cgrp);
7769
7770 return (u64) scale_load_down(tg->shares);
7771 }
7772
7773 #ifdef CONFIG_CFS_BANDWIDTH
7774 static DEFINE_MUTEX(cfs_constraints_mutex);
7775
7776 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
7777 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
7778
7779 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
7780
7781 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
7782 {
7783 int i, ret = 0, runtime_enabled, runtime_was_enabled;
7784 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7785
7786 if (tg == &root_task_group)
7787 return -EINVAL;
7788
7789 /*
7790 * Ensure we have at some amount of bandwidth every period. This is
7791 * to prevent reaching a state of large arrears when throttled via
7792 * entity_tick() resulting in prolonged exit starvation.
7793 */
7794 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
7795 return -EINVAL;
7796
7797 /*
7798 * Likewise, bound things on the otherside by preventing insane quota
7799 * periods. This also allows us to normalize in computing quota
7800 * feasibility.
7801 */
7802 if (period > max_cfs_quota_period)
7803 return -EINVAL;
7804
7805 mutex_lock(&cfs_constraints_mutex);
7806 ret = __cfs_schedulable(tg, period, quota);
7807 if (ret)
7808 goto out_unlock;
7809
7810 runtime_enabled = quota != RUNTIME_INF;
7811 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
7812 account_cfs_bandwidth_used(runtime_enabled, runtime_was_enabled);
7813 raw_spin_lock_irq(&cfs_b->lock);
7814 cfs_b->period = ns_to_ktime(period);
7815 cfs_b->quota = quota;
7816
7817 __refill_cfs_bandwidth_runtime(cfs_b);
7818 /* restart the period timer (if active) to handle new period expiry */
7819 if (runtime_enabled && cfs_b->timer_active) {
7820 /* force a reprogram */
7821 cfs_b->timer_active = 0;
7822 __start_cfs_bandwidth(cfs_b);
7823 }
7824 raw_spin_unlock_irq(&cfs_b->lock);
7825
7826 for_each_possible_cpu(i) {
7827 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
7828 struct rq *rq = cfs_rq->rq;
7829
7830 raw_spin_lock_irq(&rq->lock);
7831 cfs_rq->runtime_enabled = runtime_enabled;
7832 cfs_rq->runtime_remaining = 0;
7833
7834 if (cfs_rq->throttled)
7835 unthrottle_cfs_rq(cfs_rq);
7836 raw_spin_unlock_irq(&rq->lock);
7837 }
7838 out_unlock:
7839 mutex_unlock(&cfs_constraints_mutex);
7840
7841 return ret;
7842 }
7843
7844 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
7845 {
7846 u64 quota, period;
7847
7848 period = ktime_to_ns(tg->cfs_bandwidth.period);
7849 if (cfs_quota_us < 0)
7850 quota = RUNTIME_INF;
7851 else
7852 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
7853
7854 return tg_set_cfs_bandwidth(tg, period, quota);
7855 }
7856
7857 long tg_get_cfs_quota(struct task_group *tg)
7858 {
7859 u64 quota_us;
7860
7861 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
7862 return -1;
7863
7864 quota_us = tg->cfs_bandwidth.quota;
7865 do_div(quota_us, NSEC_PER_USEC);
7866
7867 return quota_us;
7868 }
7869
7870 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
7871 {
7872 u64 quota, period;
7873
7874 period = (u64)cfs_period_us * NSEC_PER_USEC;
7875 quota = tg->cfs_bandwidth.quota;
7876
7877 return tg_set_cfs_bandwidth(tg, period, quota);
7878 }
7879
7880 long tg_get_cfs_period(struct task_group *tg)
7881 {
7882 u64 cfs_period_us;
7883
7884 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
7885 do_div(cfs_period_us, NSEC_PER_USEC);
7886
7887 return cfs_period_us;
7888 }
7889
7890 static s64 cpu_cfs_quota_read_s64(struct cgroup *cgrp, struct cftype *cft)
7891 {
7892 return tg_get_cfs_quota(cgroup_tg(cgrp));
7893 }
7894
7895 static int cpu_cfs_quota_write_s64(struct cgroup *cgrp, struct cftype *cftype,
7896 s64 cfs_quota_us)
7897 {
7898 return tg_set_cfs_quota(cgroup_tg(cgrp), cfs_quota_us);
7899 }
7900
7901 static u64 cpu_cfs_period_read_u64(struct cgroup *cgrp, struct cftype *cft)
7902 {
7903 return tg_get_cfs_period(cgroup_tg(cgrp));
7904 }
7905
7906 static int cpu_cfs_period_write_u64(struct cgroup *cgrp, struct cftype *cftype,
7907 u64 cfs_period_us)
7908 {
7909 return tg_set_cfs_period(cgroup_tg(cgrp), cfs_period_us);
7910 }
7911
7912 struct cfs_schedulable_data {
7913 struct task_group *tg;
7914 u64 period, quota;
7915 };
7916
7917 /*
7918 * normalize group quota/period to be quota/max_period
7919 * note: units are usecs
7920 */
7921 static u64 normalize_cfs_quota(struct task_group *tg,
7922 struct cfs_schedulable_data *d)
7923 {
7924 u64 quota, period;
7925
7926 if (tg == d->tg) {
7927 period = d->period;
7928 quota = d->quota;
7929 } else {
7930 period = tg_get_cfs_period(tg);
7931 quota = tg_get_cfs_quota(tg);
7932 }
7933
7934 /* note: these should typically be equivalent */
7935 if (quota == RUNTIME_INF || quota == -1)
7936 return RUNTIME_INF;
7937
7938 return to_ratio(period, quota);
7939 }
7940
7941 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
7942 {
7943 struct cfs_schedulable_data *d = data;
7944 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7945 s64 quota = 0, parent_quota = -1;
7946
7947 if (!tg->parent) {
7948 quota = RUNTIME_INF;
7949 } else {
7950 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
7951
7952 quota = normalize_cfs_quota(tg, d);
7953 parent_quota = parent_b->hierarchal_quota;
7954
7955 /*
7956 * ensure max(child_quota) <= parent_quota, inherit when no
7957 * limit is set
7958 */
7959 if (quota == RUNTIME_INF)
7960 quota = parent_quota;
7961 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
7962 return -EINVAL;
7963 }
7964 cfs_b->hierarchal_quota = quota;
7965
7966 return 0;
7967 }
7968
7969 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
7970 {
7971 int ret;
7972 struct cfs_schedulable_data data = {
7973 .tg = tg,
7974 .period = period,
7975 .quota = quota,
7976 };
7977
7978 if (quota != RUNTIME_INF) {
7979 do_div(data.period, NSEC_PER_USEC);
7980 do_div(data.quota, NSEC_PER_USEC);
7981 }
7982
7983 rcu_read_lock();
7984 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
7985 rcu_read_unlock();
7986
7987 return ret;
7988 }
7989
7990 static int cpu_stats_show(struct cgroup *cgrp, struct cftype *cft,
7991 struct cgroup_map_cb *cb)
7992 {
7993 struct task_group *tg = cgroup_tg(cgrp);
7994 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
7995
7996 cb->fill(cb, "nr_periods", cfs_b->nr_periods);
7997 cb->fill(cb, "nr_throttled", cfs_b->nr_throttled);
7998 cb->fill(cb, "throttled_time", cfs_b->throttled_time);
7999
8000 return 0;
8001 }
8002 #endif /* CONFIG_CFS_BANDWIDTH */
8003 #endif /* CONFIG_FAIR_GROUP_SCHED */
8004
8005 #ifdef CONFIG_RT_GROUP_SCHED
8006 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8007 s64 val)
8008 {
8009 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8010 }
8011
8012 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8013 {
8014 return sched_group_rt_runtime(cgroup_tg(cgrp));
8015 }
8016
8017 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8018 u64 rt_period_us)
8019 {
8020 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8021 }
8022
8023 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8024 {
8025 return sched_group_rt_period(cgroup_tg(cgrp));
8026 }
8027 #endif /* CONFIG_RT_GROUP_SCHED */
8028
8029 static struct cftype cpu_files[] = {
8030 #ifdef CONFIG_FAIR_GROUP_SCHED
8031 {
8032 .name = "shares",
8033 .read_u64 = cpu_shares_read_u64,
8034 .write_u64 = cpu_shares_write_u64,
8035 },
8036 #endif
8037 #ifdef CONFIG_CFS_BANDWIDTH
8038 {
8039 .name = "cfs_quota_us",
8040 .read_s64 = cpu_cfs_quota_read_s64,
8041 .write_s64 = cpu_cfs_quota_write_s64,
8042 },
8043 {
8044 .name = "cfs_period_us",
8045 .read_u64 = cpu_cfs_period_read_u64,
8046 .write_u64 = cpu_cfs_period_write_u64,
8047 },
8048 {
8049 .name = "stat",
8050 .read_map = cpu_stats_show,
8051 },
8052 #endif
8053 #ifdef CONFIG_RT_GROUP_SCHED
8054 {
8055 .name = "rt_runtime_us",
8056 .read_s64 = cpu_rt_runtime_read,
8057 .write_s64 = cpu_rt_runtime_write,
8058 },
8059 {
8060 .name = "rt_period_us",
8061 .read_u64 = cpu_rt_period_read_uint,
8062 .write_u64 = cpu_rt_period_write_uint,
8063 },
8064 #endif
8065 { } /* terminate */
8066 };
8067
8068 struct cgroup_subsys cpu_cgroup_subsys = {
8069 .name = "cpu",
8070 .css_alloc = cpu_cgroup_css_alloc,
8071 .css_free = cpu_cgroup_css_free,
8072 .css_online = cpu_cgroup_css_online,
8073 .css_offline = cpu_cgroup_css_offline,
8074 .can_attach = cpu_cgroup_can_attach,
8075 .attach = cpu_cgroup_attach,
8076 .exit = cpu_cgroup_exit,
8077 .subsys_id = cpu_cgroup_subsys_id,
8078 .base_cftypes = cpu_files,
8079 .early_init = 1,
8080 };
8081
8082 #endif /* CONFIG_CGROUP_SCHED */
8083
8084 #ifdef CONFIG_CGROUP_CPUACCT
8085
8086 /*
8087 * CPU accounting code for task groups.
8088 *
8089 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8090 * (balbir@in.ibm.com).
8091 */
8092
8093 struct cpuacct root_cpuacct;
8094
8095 /* create a new cpu accounting group */
8096 static struct cgroup_subsys_state *cpuacct_css_alloc(struct cgroup *cgrp)
8097 {
8098 struct cpuacct *ca;
8099
8100 if (!cgrp->parent)
8101 return &root_cpuacct.css;
8102
8103 ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8104 if (!ca)
8105 goto out;
8106
8107 ca->cpuusage = alloc_percpu(u64);
8108 if (!ca->cpuusage)
8109 goto out_free_ca;
8110
8111 ca->cpustat = alloc_percpu(struct kernel_cpustat);
8112 if (!ca->cpustat)
8113 goto out_free_cpuusage;
8114
8115 return &ca->css;
8116
8117 out_free_cpuusage:
8118 free_percpu(ca->cpuusage);
8119 out_free_ca:
8120 kfree(ca);
8121 out:
8122 return ERR_PTR(-ENOMEM);
8123 }
8124
8125 /* destroy an existing cpu accounting group */
8126 static void cpuacct_css_free(struct cgroup *cgrp)
8127 {
8128 struct cpuacct *ca = cgroup_ca(cgrp);
8129
8130 free_percpu(ca->cpustat);
8131 free_percpu(ca->cpuusage);
8132 kfree(ca);
8133 }
8134
8135 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
8136 {
8137 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8138 u64 data;
8139
8140 #ifndef CONFIG_64BIT
8141 /*
8142 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
8143 */
8144 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8145 data = *cpuusage;
8146 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8147 #else
8148 data = *cpuusage;
8149 #endif
8150
8151 return data;
8152 }
8153
8154 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
8155 {
8156 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8157
8158 #ifndef CONFIG_64BIT
8159 /*
8160 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
8161 */
8162 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8163 *cpuusage = val;
8164 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8165 #else
8166 *cpuusage = val;
8167 #endif
8168 }
8169
8170 /* return total cpu usage (in nanoseconds) of a group */
8171 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
8172 {
8173 struct cpuacct *ca = cgroup_ca(cgrp);
8174 u64 totalcpuusage = 0;
8175 int i;
8176
8177 for_each_present_cpu(i)
8178 totalcpuusage += cpuacct_cpuusage_read(ca, i);
8179
8180 return totalcpuusage;
8181 }
8182
8183 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
8184 u64 reset)
8185 {
8186 struct cpuacct *ca = cgroup_ca(cgrp);
8187 int err = 0;
8188 int i;
8189
8190 if (reset) {
8191 err = -EINVAL;
8192 goto out;
8193 }
8194
8195 for_each_present_cpu(i)
8196 cpuacct_cpuusage_write(ca, i, 0);
8197
8198 out:
8199 return err;
8200 }
8201
8202 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
8203 struct seq_file *m)
8204 {
8205 struct cpuacct *ca = cgroup_ca(cgroup);
8206 u64 percpu;
8207 int i;
8208
8209 for_each_present_cpu(i) {
8210 percpu = cpuacct_cpuusage_read(ca, i);
8211 seq_printf(m, "%llu ", (unsigned long long) percpu);
8212 }
8213 seq_printf(m, "\n");
8214 return 0;
8215 }
8216
8217 static const char *cpuacct_stat_desc[] = {
8218 [CPUACCT_STAT_USER] = "user",
8219 [CPUACCT_STAT_SYSTEM] = "system",
8220 };
8221
8222 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
8223 struct cgroup_map_cb *cb)
8224 {
8225 struct cpuacct *ca = cgroup_ca(cgrp);
8226 int cpu;
8227 s64 val = 0;
8228
8229 for_each_online_cpu(cpu) {
8230 struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu);
8231 val += kcpustat->cpustat[CPUTIME_USER];
8232 val += kcpustat->cpustat[CPUTIME_NICE];
8233 }
8234 val = cputime64_to_clock_t(val);
8235 cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_USER], val);
8236
8237 val = 0;
8238 for_each_online_cpu(cpu) {
8239 struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu);
8240 val += kcpustat->cpustat[CPUTIME_SYSTEM];
8241 val += kcpustat->cpustat[CPUTIME_IRQ];
8242 val += kcpustat->cpustat[CPUTIME_SOFTIRQ];
8243 }
8244
8245 val = cputime64_to_clock_t(val);
8246 cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_SYSTEM], val);
8247
8248 return 0;
8249 }
8250
8251 static struct cftype files[] = {
8252 {
8253 .name = "usage",
8254 .read_u64 = cpuusage_read,
8255 .write_u64 = cpuusage_write,
8256 },
8257 {
8258 .name = "usage_percpu",
8259 .read_seq_string = cpuacct_percpu_seq_read,
8260 },
8261 {
8262 .name = "stat",
8263 .read_map = cpuacct_stats_show,
8264 },
8265 { } /* terminate */
8266 };
8267
8268 /*
8269 * charge this task's execution time to its accounting group.
8270 *
8271 * called with rq->lock held.
8272 */
8273 void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8274 {
8275 struct cpuacct *ca;
8276 int cpu;
8277
8278 if (unlikely(!cpuacct_subsys.active))
8279 return;
8280
8281 cpu = task_cpu(tsk);
8282
8283 rcu_read_lock();
8284
8285 ca = task_ca(tsk);
8286
8287 for (; ca; ca = parent_ca(ca)) {
8288 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8289 *cpuusage += cputime;
8290 }
8291
8292 rcu_read_unlock();
8293 }
8294
8295 struct cgroup_subsys cpuacct_subsys = {
8296 .name = "cpuacct",
8297 .css_alloc = cpuacct_css_alloc,
8298 .css_free = cpuacct_css_free,
8299 .subsys_id = cpuacct_subsys_id,
8300 .base_cftypes = files,
8301 };
8302 #endif /* CONFIG_CGROUP_CPUACCT */
8303
8304 void dump_cpu_task(int cpu)
8305 {
8306 pr_info("Task dump for CPU %d:\n", cpu);
8307 sched_show_task(cpu_curr(cpu));
8308 }
This page took 0.185442 seconds and 6 git commands to generate.