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