~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/kernel/sched/fair.c

Version: ~ [ linux-5.7 ] ~ [ linux-5.6.15 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.43 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.125 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.182 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.225 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.225 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.84 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 // SPDX-License-Identifier: GPL-2.0
  2 /*
  3  * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
  4  *
  5  *  Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  6  *
  7  *  Interactivity improvements by Mike Galbraith
  8  *  (C) 2007 Mike Galbraith <efault@gmx.de>
  9  *
 10  *  Various enhancements by Dmitry Adamushko.
 11  *  (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
 12  *
 13  *  Group scheduling enhancements by Srivatsa Vaddagiri
 14  *  Copyright IBM Corporation, 2007
 15  *  Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
 16  *
 17  *  Scaled math optimizations by Thomas Gleixner
 18  *  Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
 19  *
 20  *  Adaptive scheduling granularity, math enhancements by Peter Zijlstra
 21  *  Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra
 22  */
 23 #include "sched.h"
 24 
 25 #include <trace/events/sched.h>
 26 
 27 /*
 28  * Targeted preemption latency for CPU-bound tasks:
 29  *
 30  * NOTE: this latency value is not the same as the concept of
 31  * 'timeslice length' - timeslices in CFS are of variable length
 32  * and have no persistent notion like in traditional, time-slice
 33  * based scheduling concepts.
 34  *
 35  * (to see the precise effective timeslice length of your workload,
 36  *  run vmstat and monitor the context-switches (cs) field)
 37  *
 38  * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
 39  */
 40 unsigned int sysctl_sched_latency                       = 6000000ULL;
 41 static unsigned int normalized_sysctl_sched_latency     = 6000000ULL;
 42 
 43 /*
 44  * The initial- and re-scaling of tunables is configurable
 45  *
 46  * Options are:
 47  *
 48  *   SCHED_TUNABLESCALING_NONE - unscaled, always *1
 49  *   SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
 50  *   SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
 51  *
 52  * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
 53  */
 54 enum sched_tunable_scaling sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
 55 
 56 /*
 57  * Minimal preemption granularity for CPU-bound tasks:
 58  *
 59  * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
 60  */
 61 unsigned int sysctl_sched_min_granularity                       = 750000ULL;
 62 static unsigned int normalized_sysctl_sched_min_granularity     = 750000ULL;
 63 
 64 /*
 65  * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
 66  */
 67 static unsigned int sched_nr_latency = 8;
 68 
 69 /*
 70  * After fork, child runs first. If set to 0 (default) then
 71  * parent will (try to) run first.
 72  */
 73 unsigned int sysctl_sched_child_runs_first __read_mostly;
 74 
 75 /*
 76  * SCHED_OTHER wake-up granularity.
 77  *
 78  * This option delays the preemption effects of decoupled workloads
 79  * and reduces their over-scheduling. Synchronous workloads will still
 80  * have immediate wakeup/sleep latencies.
 81  *
 82  * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
 83  */
 84 unsigned int sysctl_sched_wakeup_granularity                    = 1000000UL;
 85 static unsigned int normalized_sysctl_sched_wakeup_granularity  = 1000000UL;
 86 
 87 const_debug unsigned int sysctl_sched_migration_cost    = 500000UL;
 88 
 89 #ifdef CONFIG_SMP
 90 /*
 91  * For asym packing, by default the lower numbered CPU has higher priority.
 92  */
 93 int __weak arch_asym_cpu_priority(int cpu)
 94 {
 95         return -cpu;
 96 }
 97 
 98 /*
 99  * The margin used when comparing utilization with CPU capacity:
100  * util * margin < capacity * 1024
101  *
102  * (default: ~20%)
103  */
104 static unsigned int capacity_margin                     = 1280;
105 #endif
106 
107 #ifdef CONFIG_CFS_BANDWIDTH
108 /*
109  * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
110  * each time a cfs_rq requests quota.
111  *
112  * Note: in the case that the slice exceeds the runtime remaining (either due
113  * to consumption or the quota being specified to be smaller than the slice)
114  * we will always only issue the remaining available time.
115  *
116  * (default: 5 msec, units: microseconds)
117  */
118 unsigned int sysctl_sched_cfs_bandwidth_slice           = 5000UL;
119 #endif
120 
121 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
122 {
123         lw->weight += inc;
124         lw->inv_weight = 0;
125 }
126 
127 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
128 {
129         lw->weight -= dec;
130         lw->inv_weight = 0;
131 }
132 
133 static inline void update_load_set(struct load_weight *lw, unsigned long w)
134 {
135         lw->weight = w;
136         lw->inv_weight = 0;
137 }
138 
139 /*
140  * Increase the granularity value when there are more CPUs,
141  * because with more CPUs the 'effective latency' as visible
142  * to users decreases. But the relationship is not linear,
143  * so pick a second-best guess by going with the log2 of the
144  * number of CPUs.
145  *
146  * This idea comes from the SD scheduler of Con Kolivas:
147  */
148 static unsigned int get_update_sysctl_factor(void)
149 {
150         unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
151         unsigned int factor;
152 
153         switch (sysctl_sched_tunable_scaling) {
154         case SCHED_TUNABLESCALING_NONE:
155                 factor = 1;
156                 break;
157         case SCHED_TUNABLESCALING_LINEAR:
158                 factor = cpus;
159                 break;
160         case SCHED_TUNABLESCALING_LOG:
161         default:
162                 factor = 1 + ilog2(cpus);
163                 break;
164         }
165 
166         return factor;
167 }
168 
169 static void update_sysctl(void)
170 {
171         unsigned int factor = get_update_sysctl_factor();
172 
173 #define SET_SYSCTL(name) \
174         (sysctl_##name = (factor) * normalized_sysctl_##name)
175         SET_SYSCTL(sched_min_granularity);
176         SET_SYSCTL(sched_latency);
177         SET_SYSCTL(sched_wakeup_granularity);
178 #undef SET_SYSCTL
179 }
180 
181 void sched_init_granularity(void)
182 {
183         update_sysctl();
184 }
185 
186 #define WMULT_CONST     (~0U)
187 #define WMULT_SHIFT     32
188 
189 static void __update_inv_weight(struct load_weight *lw)
190 {
191         unsigned long w;
192 
193         if (likely(lw->inv_weight))
194                 return;
195 
196         w = scale_load_down(lw->weight);
197 
198         if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
199                 lw->inv_weight = 1;
200         else if (unlikely(!w))
201                 lw->inv_weight = WMULT_CONST;
202         else
203                 lw->inv_weight = WMULT_CONST / w;
204 }
205 
206 /*
207  * delta_exec * weight / lw.weight
208  *   OR
209  * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
210  *
211  * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
212  * we're guaranteed shift stays positive because inv_weight is guaranteed to
213  * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
214  *
215  * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
216  * weight/lw.weight <= 1, and therefore our shift will also be positive.
217  */
218 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
219 {
220         u64 fact = scale_load_down(weight);
221         int shift = WMULT_SHIFT;
222 
223         __update_inv_weight(lw);
224 
225         if (unlikely(fact >> 32)) {
226                 while (fact >> 32) {
227                         fact >>= 1;
228                         shift--;
229                 }
230         }
231 
232         /* hint to use a 32x32->64 mul */
233         fact = (u64)(u32)fact * lw->inv_weight;
234 
235         while (fact >> 32) {
236                 fact >>= 1;
237                 shift--;
238         }
239 
240         return mul_u64_u32_shr(delta_exec, fact, shift);
241 }
242 
243 
244 const struct sched_class fair_sched_class;
245 
246 /**************************************************************
247  * CFS operations on generic schedulable entities:
248  */
249 
250 #ifdef CONFIG_FAIR_GROUP_SCHED
251 
252 /* cpu runqueue to which this cfs_rq is attached */
253 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
254 {
255         return cfs_rq->rq;
256 }
257 
258 static inline struct task_struct *task_of(struct sched_entity *se)
259 {
260         SCHED_WARN_ON(!entity_is_task(se));
261         return container_of(se, struct task_struct, se);
262 }
263 
264 /* Walk up scheduling entities hierarchy */
265 #define for_each_sched_entity(se) \
266                 for (; se; se = se->parent)
267 
268 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
269 {
270         return p->se.cfs_rq;
271 }
272 
273 /* runqueue on which this entity is (to be) queued */
274 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
275 {
276         return se->cfs_rq;
277 }
278 
279 /* runqueue "owned" by this group */
280 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
281 {
282         return grp->my_q;
283 }
284 
285 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
286 {
287         if (!cfs_rq->on_list) {
288                 struct rq *rq = rq_of(cfs_rq);
289                 int cpu = cpu_of(rq);
290                 /*
291                  * Ensure we either appear before our parent (if already
292                  * enqueued) or force our parent to appear after us when it is
293                  * enqueued. The fact that we always enqueue bottom-up
294                  * reduces this to two cases and a special case for the root
295                  * cfs_rq. Furthermore, it also means that we will always reset
296                  * tmp_alone_branch either when the branch is connected
297                  * to a tree or when we reach the beg of the tree
298                  */
299                 if (cfs_rq->tg->parent &&
300                     cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
301                         /*
302                          * If parent is already on the list, we add the child
303                          * just before. Thanks to circular linked property of
304                          * the list, this means to put the child at the tail
305                          * of the list that starts by parent.
306                          */
307                         list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
308                                 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
309                         /*
310                          * The branch is now connected to its tree so we can
311                          * reset tmp_alone_branch to the beginning of the
312                          * list.
313                          */
314                         rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
315                 } else if (!cfs_rq->tg->parent) {
316                         /*
317                          * cfs rq without parent should be put
318                          * at the tail of the list.
319                          */
320                         list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
321                                 &rq->leaf_cfs_rq_list);
322                         /*
323                          * We have reach the beg of a tree so we can reset
324                          * tmp_alone_branch to the beginning of the list.
325                          */
326                         rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
327                 } else {
328                         /*
329                          * The parent has not already been added so we want to
330                          * make sure that it will be put after us.
331                          * tmp_alone_branch points to the beg of the branch
332                          * where we will add parent.
333                          */
334                         list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
335                                 rq->tmp_alone_branch);
336                         /*
337                          * update tmp_alone_branch to points to the new beg
338                          * of the branch
339                          */
340                         rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
341                 }
342 
343                 cfs_rq->on_list = 1;
344         }
345 }
346 
347 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
348 {
349         if (cfs_rq->on_list) {
350                 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
351                 cfs_rq->on_list = 0;
352         }
353 }
354 
355 /* Iterate through all leaf cfs_rq's on a runqueue: */
356 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
357         list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
358 
359 /* Do the two (enqueued) entities belong to the same group ? */
360 static inline struct cfs_rq *
361 is_same_group(struct sched_entity *se, struct sched_entity *pse)
362 {
363         if (se->cfs_rq == pse->cfs_rq)
364                 return se->cfs_rq;
365 
366         return NULL;
367 }
368 
369 static inline struct sched_entity *parent_entity(struct sched_entity *se)
370 {
371         return se->parent;
372 }
373 
374 static void
375 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
376 {
377         int se_depth, pse_depth;
378 
379         /*
380          * preemption test can be made between sibling entities who are in the
381          * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
382          * both tasks until we find their ancestors who are siblings of common
383          * parent.
384          */
385 
386         /* First walk up until both entities are at same depth */
387         se_depth = (*se)->depth;
388         pse_depth = (*pse)->depth;
389 
390         while (se_depth > pse_depth) {
391                 se_depth--;
392                 *se = parent_entity(*se);
393         }
394 
395         while (pse_depth > se_depth) {
396                 pse_depth--;
397                 *pse = parent_entity(*pse);
398         }
399 
400         while (!is_same_group(*se, *pse)) {
401                 *se = parent_entity(*se);
402                 *pse = parent_entity(*pse);
403         }
404 }
405 
406 #else   /* !CONFIG_FAIR_GROUP_SCHED */
407 
408 static inline struct task_struct *task_of(struct sched_entity *se)
409 {
410         return container_of(se, struct task_struct, se);
411 }
412 
413 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
414 {
415         return container_of(cfs_rq, struct rq, cfs);
416 }
417 
418 
419 #define for_each_sched_entity(se) \
420                 for (; se; se = NULL)
421 
422 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
423 {
424         return &task_rq(p)->cfs;
425 }
426 
427 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
428 {
429         struct task_struct *p = task_of(se);
430         struct rq *rq = task_rq(p);
431 
432         return &rq->cfs;
433 }
434 
435 /* runqueue "owned" by this group */
436 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
437 {
438         return NULL;
439 }
440 
441 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
442 {
443 }
444 
445 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
446 {
447 }
448 
449 #define for_each_leaf_cfs_rq(rq, cfs_rq)        \
450                 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
451 
452 static inline struct sched_entity *parent_entity(struct sched_entity *se)
453 {
454         return NULL;
455 }
456 
457 static inline void
458 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
459 {
460 }
461 
462 #endif  /* CONFIG_FAIR_GROUP_SCHED */
463 
464 static __always_inline
465 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
466 
467 /**************************************************************
468  * Scheduling class tree data structure manipulation methods:
469  */
470 
471 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
472 {
473         s64 delta = (s64)(vruntime - max_vruntime);
474         if (delta > 0)
475                 max_vruntime = vruntime;
476 
477         return max_vruntime;
478 }
479 
480 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
481 {
482         s64 delta = (s64)(vruntime - min_vruntime);
483         if (delta < 0)
484                 min_vruntime = vruntime;
485 
486         return min_vruntime;
487 }
488 
489 static inline int entity_before(struct sched_entity *a,
490                                 struct sched_entity *b)
491 {
492         return (s64)(a->vruntime - b->vruntime) < 0;
493 }
494 
495 static void update_min_vruntime(struct cfs_rq *cfs_rq)
496 {
497         struct sched_entity *curr = cfs_rq->curr;
498         struct rb_node *leftmost = rb_first_cached(&cfs_rq->tasks_timeline);
499 
500         u64 vruntime = cfs_rq->min_vruntime;
501 
502         if (curr) {
503                 if (curr->on_rq)
504                         vruntime = curr->vruntime;
505                 else
506                         curr = NULL;
507         }
508 
509         if (leftmost) { /* non-empty tree */
510                 struct sched_entity *se;
511                 se = rb_entry(leftmost, struct sched_entity, run_node);
512 
513                 if (!curr)
514                         vruntime = se->vruntime;
515                 else
516                         vruntime = min_vruntime(vruntime, se->vruntime);
517         }
518 
519         /* ensure we never gain time by being placed backwards. */
520         cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
521 #ifndef CONFIG_64BIT
522         smp_wmb();
523         cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
524 #endif
525 }
526 
527 /*
528  * Enqueue an entity into the rb-tree:
529  */
530 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
531 {
532         struct rb_node **link = &cfs_rq->tasks_timeline.rb_root.rb_node;
533         struct rb_node *parent = NULL;
534         struct sched_entity *entry;
535         bool leftmost = true;
536 
537         /*
538          * Find the right place in the rbtree:
539          */
540         while (*link) {
541                 parent = *link;
542                 entry = rb_entry(parent, struct sched_entity, run_node);
543                 /*
544                  * We dont care about collisions. Nodes with
545                  * the same key stay together.
546                  */
547                 if (entity_before(se, entry)) {
548                         link = &parent->rb_left;
549                 } else {
550                         link = &parent->rb_right;
551                         leftmost = false;
552                 }
553         }
554 
555         rb_link_node(&se->run_node, parent, link);
556         rb_insert_color_cached(&se->run_node,
557                                &cfs_rq->tasks_timeline, leftmost);
558 }
559 
560 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
561 {
562         rb_erase_cached(&se->run_node, &cfs_rq->tasks_timeline);
563 }
564 
565 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
566 {
567         struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
568 
569         if (!left)
570                 return NULL;
571 
572         return rb_entry(left, struct sched_entity, run_node);
573 }
574 
575 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
576 {
577         struct rb_node *next = rb_next(&se->run_node);
578 
579         if (!next)
580                 return NULL;
581 
582         return rb_entry(next, struct sched_entity, run_node);
583 }
584 
585 #ifdef CONFIG_SCHED_DEBUG
586 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
587 {
588         struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
589 
590         if (!last)
591                 return NULL;
592 
593         return rb_entry(last, struct sched_entity, run_node);
594 }
595 
596 /**************************************************************
597  * Scheduling class statistics methods:
598  */
599 
600 int sched_proc_update_handler(struct ctl_table *table, int write,
601                 void __user *buffer, size_t *lenp,
602                 loff_t *ppos)
603 {
604         int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
605         unsigned int factor = get_update_sysctl_factor();
606 
607         if (ret || !write)
608                 return ret;
609 
610         sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
611                                         sysctl_sched_min_granularity);
612 
613 #define WRT_SYSCTL(name) \
614         (normalized_sysctl_##name = sysctl_##name / (factor))
615         WRT_SYSCTL(sched_min_granularity);
616         WRT_SYSCTL(sched_latency);
617         WRT_SYSCTL(sched_wakeup_granularity);
618 #undef WRT_SYSCTL
619 
620         return 0;
621 }
622 #endif
623 
624 /*
625  * delta /= w
626  */
627 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
628 {
629         if (unlikely(se->load.weight != NICE_0_LOAD))
630                 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
631 
632         return delta;
633 }
634 
635 /*
636  * The idea is to set a period in which each task runs once.
637  *
638  * When there are too many tasks (sched_nr_latency) we have to stretch
639  * this period because otherwise the slices get too small.
640  *
641  * p = (nr <= nl) ? l : l*nr/nl
642  */
643 static u64 __sched_period(unsigned long nr_running)
644 {
645         if (unlikely(nr_running > sched_nr_latency))
646                 return nr_running * sysctl_sched_min_granularity;
647         else
648                 return sysctl_sched_latency;
649 }
650 
651 /*
652  * We calculate the wall-time slice from the period by taking a part
653  * proportional to the weight.
654  *
655  * s = p*P[w/rw]
656  */
657 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
658 {
659         u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
660 
661         for_each_sched_entity(se) {
662                 struct load_weight *load;
663                 struct load_weight lw;
664 
665                 cfs_rq = cfs_rq_of(se);
666                 load = &cfs_rq->load;
667 
668                 if (unlikely(!se->on_rq)) {
669                         lw = cfs_rq->load;
670 
671                         update_load_add(&lw, se->load.weight);
672                         load = &lw;
673                 }
674                 slice = __calc_delta(slice, se->load.weight, load);
675         }
676         return slice;
677 }
678 
679 /*
680  * We calculate the vruntime slice of a to-be-inserted task.
681  *
682  * vs = s/w
683  */
684 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
685 {
686         return calc_delta_fair(sched_slice(cfs_rq, se), se);
687 }
688 
689 #ifdef CONFIG_SMP
690 #include "pelt.h"
691 #include "sched-pelt.h"
692 
693 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
694 static unsigned long task_h_load(struct task_struct *p);
695 static unsigned long capacity_of(int cpu);
696 
697 /* Give new sched_entity start runnable values to heavy its load in infant time */
698 void init_entity_runnable_average(struct sched_entity *se)
699 {
700         struct sched_avg *sa = &se->avg;
701 
702         memset(sa, 0, sizeof(*sa));
703 
704         /*
705          * Tasks are initialized with full load to be seen as heavy tasks until
706          * they get a chance to stabilize to their real load level.
707          * Group entities are initialized with zero load to reflect the fact that
708          * nothing has been attached to the task group yet.
709          */
710         if (entity_is_task(se))
711                 sa->runnable_load_avg = sa->load_avg = scale_load_down(se->load.weight);
712 
713         se->runnable_weight = se->load.weight;
714 
715         /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
716 }
717 
718 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
719 static void attach_entity_cfs_rq(struct sched_entity *se);
720 
721 /*
722  * With new tasks being created, their initial util_avgs are extrapolated
723  * based on the cfs_rq's current util_avg:
724  *
725  *   util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
726  *
727  * However, in many cases, the above util_avg does not give a desired
728  * value. Moreover, the sum of the util_avgs may be divergent, such
729  * as when the series is a harmonic series.
730  *
731  * To solve this problem, we also cap the util_avg of successive tasks to
732  * only 1/2 of the left utilization budget:
733  *
734  *   util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
735  *
736  * where n denotes the nth task and cpu_scale the CPU capacity.
737  *
738  * For example, for a CPU with 1024 of capacity, a simplest series from
739  * the beginning would be like:
740  *
741  *  task  util_avg: 512, 256, 128,  64,  32,   16,    8, ...
742  * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
743  *
744  * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
745  * if util_avg > util_avg_cap.
746  */
747 void post_init_entity_util_avg(struct sched_entity *se)
748 {
749         struct cfs_rq *cfs_rq = cfs_rq_of(se);
750         struct sched_avg *sa = &se->avg;
751         long cpu_scale = arch_scale_cpu_capacity(NULL, cpu_of(rq_of(cfs_rq)));
752         long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
753 
754         if (cap > 0) {
755                 if (cfs_rq->avg.util_avg != 0) {
756                         sa->util_avg  = cfs_rq->avg.util_avg * se->load.weight;
757                         sa->util_avg /= (cfs_rq->avg.load_avg + 1);
758 
759                         if (sa->util_avg > cap)
760                                 sa->util_avg = cap;
761                 } else {
762                         sa->util_avg = cap;
763                 }
764         }
765 
766         if (entity_is_task(se)) {
767                 struct task_struct *p = task_of(se);
768                 if (p->sched_class != &fair_sched_class) {
769                         /*
770                          * For !fair tasks do:
771                          *
772                         update_cfs_rq_load_avg(now, cfs_rq);
773                         attach_entity_load_avg(cfs_rq, se, 0);
774                         switched_from_fair(rq, p);
775                          *
776                          * such that the next switched_to_fair() has the
777                          * expected state.
778                          */
779                         se->avg.last_update_time = cfs_rq_clock_task(cfs_rq);
780                         return;
781                 }
782         }
783 
784         attach_entity_cfs_rq(se);
785 }
786 
787 #else /* !CONFIG_SMP */
788 void init_entity_runnable_average(struct sched_entity *se)
789 {
790 }
791 void post_init_entity_util_avg(struct sched_entity *se)
792 {
793 }
794 static void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
795 {
796 }
797 #endif /* CONFIG_SMP */
798 
799 /*
800  * Update the current task's runtime statistics.
801  */
802 static void update_curr(struct cfs_rq *cfs_rq)
803 {
804         struct sched_entity *curr = cfs_rq->curr;
805         u64 now = rq_clock_task(rq_of(cfs_rq));
806         u64 delta_exec;
807 
808         if (unlikely(!curr))
809                 return;
810 
811         delta_exec = now - curr->exec_start;
812         if (unlikely((s64)delta_exec <= 0))
813                 return;
814 
815         curr->exec_start = now;
816 
817         schedstat_set(curr->statistics.exec_max,
818                       max(delta_exec, curr->statistics.exec_max));
819 
820         curr->sum_exec_runtime += delta_exec;
821         schedstat_add(cfs_rq->exec_clock, delta_exec);
822 
823         curr->vruntime += calc_delta_fair(delta_exec, curr);
824         update_min_vruntime(cfs_rq);
825 
826         if (entity_is_task(curr)) {
827                 struct task_struct *curtask = task_of(curr);
828 
829                 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
830                 cgroup_account_cputime(curtask, delta_exec);
831                 account_group_exec_runtime(curtask, delta_exec);
832         }
833 
834         account_cfs_rq_runtime(cfs_rq, delta_exec);
835 }
836 
837 static void update_curr_fair(struct rq *rq)
838 {
839         update_curr(cfs_rq_of(&rq->curr->se));
840 }
841 
842 static inline void
843 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
844 {
845         u64 wait_start, prev_wait_start;
846 
847         if (!schedstat_enabled())
848                 return;
849 
850         wait_start = rq_clock(rq_of(cfs_rq));
851         prev_wait_start = schedstat_val(se->statistics.wait_start);
852 
853         if (entity_is_task(se) && task_on_rq_migrating(task_of(se)) &&
854             likely(wait_start > prev_wait_start))
855                 wait_start -= prev_wait_start;
856 
857         __schedstat_set(se->statistics.wait_start, wait_start);
858 }
859 
860 static inline void
861 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
862 {
863         struct task_struct *p;
864         u64 delta;
865 
866         if (!schedstat_enabled())
867                 return;
868 
869         delta = rq_clock(rq_of(cfs_rq)) - schedstat_val(se->statistics.wait_start);
870 
871         if (entity_is_task(se)) {
872                 p = task_of(se);
873                 if (task_on_rq_migrating(p)) {
874                         /*
875                          * Preserve migrating task's wait time so wait_start
876                          * time stamp can be adjusted to accumulate wait time
877                          * prior to migration.
878                          */
879                         __schedstat_set(se->statistics.wait_start, delta);
880                         return;
881                 }
882                 trace_sched_stat_wait(p, delta);
883         }
884 
885         __schedstat_set(se->statistics.wait_max,
886                       max(schedstat_val(se->statistics.wait_max), delta));
887         __schedstat_inc(se->statistics.wait_count);
888         __schedstat_add(se->statistics.wait_sum, delta);
889         __schedstat_set(se->statistics.wait_start, 0);
890 }
891 
892 static inline void
893 update_stats_enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
894 {
895         struct task_struct *tsk = NULL;
896         u64 sleep_start, block_start;
897 
898         if (!schedstat_enabled())
899                 return;
900 
901         sleep_start = schedstat_val(se->statistics.sleep_start);
902         block_start = schedstat_val(se->statistics.block_start);
903 
904         if (entity_is_task(se))
905                 tsk = task_of(se);
906 
907         if (sleep_start) {
908                 u64 delta = rq_clock(rq_of(cfs_rq)) - sleep_start;
909 
910                 if ((s64)delta < 0)
911                         delta = 0;
912 
913                 if (unlikely(delta > schedstat_val(se->statistics.sleep_max)))
914                         __schedstat_set(se->statistics.sleep_max, delta);
915 
916                 __schedstat_set(se->statistics.sleep_start, 0);
917                 __schedstat_add(se->statistics.sum_sleep_runtime, delta);
918 
919                 if (tsk) {
920                         account_scheduler_latency(tsk, delta >> 10, 1);
921                         trace_sched_stat_sleep(tsk, delta);
922                 }
923         }
924         if (block_start) {
925                 u64 delta = rq_clock(rq_of(cfs_rq)) - block_start;
926 
927                 if ((s64)delta < 0)
928                         delta = 0;
929 
930                 if (unlikely(delta > schedstat_val(se->statistics.block_max)))
931                         __schedstat_set(se->statistics.block_max, delta);
932 
933                 __schedstat_set(se->statistics.block_start, 0);
934                 __schedstat_add(se->statistics.sum_sleep_runtime, delta);
935 
936                 if (tsk) {
937                         if (tsk->in_iowait) {
938                                 __schedstat_add(se->statistics.iowait_sum, delta);
939                                 __schedstat_inc(se->statistics.iowait_count);
940                                 trace_sched_stat_iowait(tsk, delta);
941                         }
942 
943                         trace_sched_stat_blocked(tsk, delta);
944 
945                         /*
946                          * Blocking time is in units of nanosecs, so shift by
947                          * 20 to get a milliseconds-range estimation of the
948                          * amount of time that the task spent sleeping:
949                          */
950                         if (unlikely(prof_on == SLEEP_PROFILING)) {
951                                 profile_hits(SLEEP_PROFILING,
952                                                 (void *)get_wchan(tsk),
953                                                 delta >> 20);
954                         }
955                         account_scheduler_latency(tsk, delta >> 10, 0);
956                 }
957         }
958 }
959 
960 /*
961  * Task is being enqueued - update stats:
962  */
963 static inline void
964 update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
965 {
966         if (!schedstat_enabled())
967                 return;
968 
969         /*
970          * Are we enqueueing a waiting task? (for current tasks
971          * a dequeue/enqueue event is a NOP)
972          */
973         if (se != cfs_rq->curr)
974                 update_stats_wait_start(cfs_rq, se);
975 
976         if (flags & ENQUEUE_WAKEUP)
977                 update_stats_enqueue_sleeper(cfs_rq, se);
978 }
979 
980 static inline void
981 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
982 {
983 
984         if (!schedstat_enabled())
985                 return;
986 
987         /*
988          * Mark the end of the wait period if dequeueing a
989          * waiting task:
990          */
991         if (se != cfs_rq->curr)
992                 update_stats_wait_end(cfs_rq, se);
993 
994         if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
995                 struct task_struct *tsk = task_of(se);
996 
997                 if (tsk->state & TASK_INTERRUPTIBLE)
998                         __schedstat_set(se->statistics.sleep_start,
999                                       rq_clock(rq_of(cfs_rq)));
1000                 if (tsk->state & TASK_UNINTERRUPTIBLE)
1001                         __schedstat_set(se->statistics.block_start,
1002                                       rq_clock(rq_of(cfs_rq)));
1003         }
1004 }
1005 
1006 /*
1007  * We are picking a new current task - update its stats:
1008  */
1009 static inline void
1010 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1011 {
1012         /*
1013          * We are starting a new run period:
1014          */
1015         se->exec_start = rq_clock_task(rq_of(cfs_rq));
1016 }
1017 
1018 /**************************************************
1019  * Scheduling class queueing methods:
1020  */
1021 
1022 #ifdef CONFIG_NUMA_BALANCING
1023 /*
1024  * Approximate time to scan a full NUMA task in ms. The task scan period is
1025  * calculated based on the tasks virtual memory size and
1026  * numa_balancing_scan_size.
1027  */
1028 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1029 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1030 
1031 /* Portion of address space to scan in MB */
1032 unsigned int sysctl_numa_balancing_scan_size = 256;
1033 
1034 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1035 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1036 
1037 struct numa_group {
1038         atomic_t refcount;
1039 
1040         spinlock_t lock; /* nr_tasks, tasks */
1041         int nr_tasks;
1042         pid_t gid;
1043         int active_nodes;
1044 
1045         struct rcu_head rcu;
1046         unsigned long total_faults;
1047         unsigned long max_faults_cpu;
1048         /*
1049          * Faults_cpu is used to decide whether memory should move
1050          * towards the CPU. As a consequence, these stats are weighted
1051          * more by CPU use than by memory faults.
1052          */
1053         unsigned long *faults_cpu;
1054         unsigned long faults[0];
1055 };
1056 
1057 static inline unsigned long group_faults_priv(struct numa_group *ng);
1058 static inline unsigned long group_faults_shared(struct numa_group *ng);
1059 
1060 static unsigned int task_nr_scan_windows(struct task_struct *p)
1061 {
1062         unsigned long rss = 0;
1063         unsigned long nr_scan_pages;
1064 
1065         /*
1066          * Calculations based on RSS as non-present and empty pages are skipped
1067          * by the PTE scanner and NUMA hinting faults should be trapped based
1068          * on resident pages
1069          */
1070         nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1071         rss = get_mm_rss(p->mm);
1072         if (!rss)
1073                 rss = nr_scan_pages;
1074 
1075         rss = round_up(rss, nr_scan_pages);
1076         return rss / nr_scan_pages;
1077 }
1078 
1079 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1080 #define MAX_SCAN_WINDOW 2560
1081 
1082 static unsigned int task_scan_min(struct task_struct *p)
1083 {
1084         unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1085         unsigned int scan, floor;
1086         unsigned int windows = 1;
1087 
1088         if (scan_size < MAX_SCAN_WINDOW)
1089                 windows = MAX_SCAN_WINDOW / scan_size;
1090         floor = 1000 / windows;
1091 
1092         scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1093         return max_t(unsigned int, floor, scan);
1094 }
1095 
1096 static unsigned int task_scan_start(struct task_struct *p)
1097 {
1098         unsigned long smin = task_scan_min(p);
1099         unsigned long period = smin;
1100 
1101         /* Scale the maximum scan period with the amount of shared memory. */
1102         if (p->numa_group) {
1103                 struct numa_group *ng = p->numa_group;
1104                 unsigned long shared = group_faults_shared(ng);
1105                 unsigned long private = group_faults_priv(ng);
1106 
1107                 period *= atomic_read(&ng->refcount);
1108                 period *= shared + 1;
1109                 period /= private + shared + 1;
1110         }
1111 
1112         return max(smin, period);
1113 }
1114 
1115 static unsigned int task_scan_max(struct task_struct *p)
1116 {
1117         unsigned long smin = task_scan_min(p);
1118         unsigned long smax;
1119 
1120         /* Watch for min being lower than max due to floor calculations */
1121         smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1122 
1123         /* Scale the maximum scan period with the amount of shared memory. */
1124         if (p->numa_group) {
1125                 struct numa_group *ng = p->numa_group;
1126                 unsigned long shared = group_faults_shared(ng);
1127                 unsigned long private = group_faults_priv(ng);
1128                 unsigned long period = smax;
1129 
1130                 period *= atomic_read(&ng->refcount);
1131                 period *= shared + 1;
1132                 period /= private + shared + 1;
1133 
1134                 smax = max(smax, period);
1135         }
1136 
1137         return max(smin, smax);
1138 }
1139 
1140 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
1141 {
1142         int mm_users = 0;
1143         struct mm_struct *mm = p->mm;
1144 
1145         if (mm) {
1146                 mm_users = atomic_read(&mm->mm_users);
1147                 if (mm_users == 1) {
1148                         mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
1149                         mm->numa_scan_seq = 0;
1150                 }
1151         }
1152         p->node_stamp                   = 0;
1153         p->numa_scan_seq                = mm ? mm->numa_scan_seq : 0;
1154         p->numa_scan_period             = sysctl_numa_balancing_scan_delay;
1155         p->numa_work.next               = &p->numa_work;
1156         p->numa_faults                  = NULL;
1157         p->numa_group                   = NULL;
1158         p->last_task_numa_placement     = 0;
1159         p->last_sum_exec_runtime        = 0;
1160 
1161         /* New address space, reset the preferred nid */
1162         if (!(clone_flags & CLONE_VM)) {
1163                 p->numa_preferred_nid = -1;
1164                 return;
1165         }
1166 
1167         /*
1168          * New thread, keep existing numa_preferred_nid which should be copied
1169          * already by arch_dup_task_struct but stagger when scans start.
1170          */
1171         if (mm) {
1172                 unsigned int delay;
1173 
1174                 delay = min_t(unsigned int, task_scan_max(current),
1175                         current->numa_scan_period * mm_users * NSEC_PER_MSEC);
1176                 delay += 2 * TICK_NSEC;
1177                 p->node_stamp = delay;
1178         }
1179 }
1180 
1181 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1182 {
1183         rq->nr_numa_running += (p->numa_preferred_nid != -1);
1184         rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1185 }
1186 
1187 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1188 {
1189         rq->nr_numa_running -= (p->numa_preferred_nid != -1);
1190         rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1191 }
1192 
1193 /* Shared or private faults. */
1194 #define NR_NUMA_HINT_FAULT_TYPES 2
1195 
1196 /* Memory and CPU locality */
1197 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1198 
1199 /* Averaged statistics, and temporary buffers. */
1200 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1201 
1202 pid_t task_numa_group_id(struct task_struct *p)
1203 {
1204         return p->numa_group ? p->numa_group->gid : 0;
1205 }
1206 
1207 /*
1208  * The averaged statistics, shared & private, memory & CPU,
1209  * occupy the first half of the array. The second half of the
1210  * array is for current counters, which are averaged into the
1211  * first set by task_numa_placement.
1212  */
1213 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1214 {
1215         return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1216 }
1217 
1218 static inline unsigned long task_faults(struct task_struct *p, int nid)
1219 {
1220         if (!p->numa_faults)
1221                 return 0;
1222 
1223         return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1224                 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1225 }
1226 
1227 static inline unsigned long group_faults(struct task_struct *p, int nid)
1228 {
1229         if (!p->numa_group)
1230                 return 0;
1231 
1232         return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1233                 p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1234 }
1235 
1236 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1237 {
1238         return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
1239                 group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
1240 }
1241 
1242 static inline unsigned long group_faults_priv(struct numa_group *ng)
1243 {
1244         unsigned long faults = 0;
1245         int node;
1246 
1247         for_each_online_node(node) {
1248                 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1249         }
1250 
1251         return faults;
1252 }
1253 
1254 static inline unsigned long group_faults_shared(struct numa_group *ng)
1255 {
1256         unsigned long faults = 0;
1257         int node;
1258 
1259         for_each_online_node(node) {
1260                 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1261         }
1262 
1263         return faults;
1264 }
1265 
1266 /*
1267  * A node triggering more than 1/3 as many NUMA faults as the maximum is
1268  * considered part of a numa group's pseudo-interleaving set. Migrations
1269  * between these nodes are slowed down, to allow things to settle down.
1270  */
1271 #define ACTIVE_NODE_FRACTION 3
1272 
1273 static bool numa_is_active_node(int nid, struct numa_group *ng)
1274 {
1275         return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1276 }
1277 
1278 /* Handle placement on systems where not all nodes are directly connected. */
1279 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1280                                         int maxdist, bool task)
1281 {
1282         unsigned long score = 0;
1283         int node;
1284 
1285         /*
1286          * All nodes are directly connected, and the same distance
1287          * from each other. No need for fancy placement algorithms.
1288          */
1289         if (sched_numa_topology_type == NUMA_DIRECT)
1290                 return 0;
1291 
1292         /*
1293          * This code is called for each node, introducing N^2 complexity,
1294          * which should be ok given the number of nodes rarely exceeds 8.
1295          */
1296         for_each_online_node(node) {
1297                 unsigned long faults;
1298                 int dist = node_distance(nid, node);
1299 
1300                 /*
1301                  * The furthest away nodes in the system are not interesting
1302                  * for placement; nid was already counted.
1303                  */
1304                 if (dist == sched_max_numa_distance || node == nid)
1305                         continue;
1306 
1307                 /*
1308                  * On systems with a backplane NUMA topology, compare groups
1309                  * of nodes, and move tasks towards the group with the most
1310                  * memory accesses. When comparing two nodes at distance
1311                  * "hoplimit", only nodes closer by than "hoplimit" are part
1312                  * of each group. Skip other nodes.
1313                  */
1314                 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1315                                         dist >= maxdist)
1316                         continue;
1317 
1318                 /* Add up the faults from nearby nodes. */
1319                 if (task)
1320                         faults = task_faults(p, node);
1321                 else
1322                         faults = group_faults(p, node);
1323 
1324                 /*
1325                  * On systems with a glueless mesh NUMA topology, there are
1326                  * no fixed "groups of nodes". Instead, nodes that are not
1327                  * directly connected bounce traffic through intermediate
1328                  * nodes; a numa_group can occupy any set of nodes.
1329                  * The further away a node is, the less the faults count.
1330                  * This seems to result in good task placement.
1331                  */
1332                 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1333                         faults *= (sched_max_numa_distance - dist);
1334                         faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
1335                 }
1336 
1337                 score += faults;
1338         }
1339 
1340         return score;
1341 }
1342 
1343 /*
1344  * These return the fraction of accesses done by a particular task, or
1345  * task group, on a particular numa node.  The group weight is given a
1346  * larger multiplier, in order to group tasks together that are almost
1347  * evenly spread out between numa nodes.
1348  */
1349 static inline unsigned long task_weight(struct task_struct *p, int nid,
1350                                         int dist)
1351 {
1352         unsigned long faults, total_faults;
1353 
1354         if (!p->numa_faults)
1355                 return 0;
1356 
1357         total_faults = p->total_numa_faults;
1358 
1359         if (!total_faults)
1360                 return 0;
1361 
1362         faults = task_faults(p, nid);
1363         faults += score_nearby_nodes(p, nid, dist, true);
1364 
1365         return 1000 * faults / total_faults;
1366 }
1367 
1368 static inline unsigned long group_weight(struct task_struct *p, int nid,
1369                                          int dist)
1370 {
1371         unsigned long faults, total_faults;
1372 
1373         if (!p->numa_group)
1374                 return 0;
1375 
1376         total_faults = p->numa_group->total_faults;
1377 
1378         if (!total_faults)
1379                 return 0;
1380 
1381         faults = group_faults(p, nid);
1382         faults += score_nearby_nodes(p, nid, dist, false);
1383 
1384         return 1000 * faults / total_faults;
1385 }
1386 
1387 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1388                                 int src_nid, int dst_cpu)
1389 {
1390         struct numa_group *ng = p->numa_group;
1391         int dst_nid = cpu_to_node(dst_cpu);
1392         int last_cpupid, this_cpupid;
1393 
1394         this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1395         last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1396 
1397         /*
1398          * Allow first faults or private faults to migrate immediately early in
1399          * the lifetime of a task. The magic number 4 is based on waiting for
1400          * two full passes of the "multi-stage node selection" test that is
1401          * executed below.
1402          */
1403         if ((p->numa_preferred_nid == -1 || p->numa_scan_seq <= 4) &&
1404             (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1405                 return true;
1406 
1407         /*
1408          * Multi-stage node selection is used in conjunction with a periodic
1409          * migration fault to build a temporal task<->page relation. By using
1410          * a two-stage filter we remove short/unlikely relations.
1411          *
1412          * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1413          * a task's usage of a particular page (n_p) per total usage of this
1414          * page (n_t) (in a given time-span) to a probability.
1415          *
1416          * Our periodic faults will sample this probability and getting the
1417          * same result twice in a row, given these samples are fully
1418          * independent, is then given by P(n)^2, provided our sample period
1419          * is sufficiently short compared to the usage pattern.
1420          *
1421          * This quadric squishes small probabilities, making it less likely we
1422          * act on an unlikely task<->page relation.
1423          */
1424         if (!cpupid_pid_unset(last_cpupid) &&
1425                                 cpupid_to_nid(last_cpupid) != dst_nid)
1426                 return false;
1427 
1428         /* Always allow migrate on private faults */
1429         if (cpupid_match_pid(p, last_cpupid))
1430                 return true;
1431 
1432         /* A shared fault, but p->numa_group has not been set up yet. */
1433         if (!ng)
1434                 return true;
1435 
1436         /*
1437          * Destination node is much more heavily used than the source
1438          * node? Allow migration.
1439          */
1440         if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1441                                         ACTIVE_NODE_FRACTION)
1442                 return true;
1443 
1444         /*
1445          * Distribute memory according to CPU & memory use on each node,
1446          * with 3/4 hysteresis to avoid unnecessary memory migrations:
1447          *
1448          * faults_cpu(dst)   3   faults_cpu(src)
1449          * --------------- * - > ---------------
1450          * faults_mem(dst)   4   faults_mem(src)
1451          */
1452         return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1453                group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1454 }
1455 
1456 static unsigned long weighted_cpuload(struct rq *rq);
1457 static unsigned long source_load(int cpu, int type);
1458 static unsigned long target_load(int cpu, int type);
1459 
1460 /* Cached statistics for all CPUs within a node */
1461 struct numa_stats {
1462         unsigned long load;
1463 
1464         /* Total compute capacity of CPUs on a node */
1465         unsigned long compute_capacity;
1466 };
1467 
1468 /*
1469  * XXX borrowed from update_sg_lb_stats
1470  */
1471 static void update_numa_stats(struct numa_stats *ns, int nid)
1472 {
1473         int cpu;
1474 
1475         memset(ns, 0, sizeof(*ns));
1476         for_each_cpu(cpu, cpumask_of_node(nid)) {
1477                 struct rq *rq = cpu_rq(cpu);
1478 
1479                 ns->load += weighted_cpuload(rq);
1480                 ns->compute_capacity += capacity_of(cpu);
1481         }
1482 
1483 }
1484 
1485 struct task_numa_env {
1486         struct task_struct *p;
1487 
1488         int src_cpu, src_nid;
1489         int dst_cpu, dst_nid;
1490 
1491         struct numa_stats src_stats, dst_stats;
1492 
1493         int imbalance_pct;
1494         int dist;
1495 
1496         struct task_struct *best_task;
1497         long best_imp;
1498         int best_cpu;
1499 };
1500 
1501 static void task_numa_assign(struct task_numa_env *env,
1502                              struct task_struct *p, long imp)
1503 {
1504         struct rq *rq = cpu_rq(env->dst_cpu);
1505 
1506         /* Bail out if run-queue part of active NUMA balance. */
1507         if (xchg(&rq->numa_migrate_on, 1))
1508                 return;
1509 
1510         /*
1511          * Clear previous best_cpu/rq numa-migrate flag, since task now
1512          * found a better CPU to move/swap.
1513          */
1514         if (env->best_cpu != -1) {
1515                 rq = cpu_rq(env->best_cpu);
1516                 WRITE_ONCE(rq->numa_migrate_on, 0);
1517         }
1518 
1519         if (env->best_task)
1520                 put_task_struct(env->best_task);
1521         if (p)
1522                 get_task_struct(p);
1523 
1524         env->best_task = p;
1525         env->best_imp = imp;
1526         env->best_cpu = env->dst_cpu;
1527 }
1528 
1529 static bool load_too_imbalanced(long src_load, long dst_load,
1530                                 struct task_numa_env *env)
1531 {
1532         long imb, old_imb;
1533         long orig_src_load, orig_dst_load;
1534         long src_capacity, dst_capacity;
1535 
1536         /*
1537          * The load is corrected for the CPU capacity available on each node.
1538          *
1539          * src_load        dst_load
1540          * ------------ vs ---------
1541          * src_capacity    dst_capacity
1542          */
1543         src_capacity = env->src_stats.compute_capacity;
1544         dst_capacity = env->dst_stats.compute_capacity;
1545 
1546         imb = abs(dst_load * src_capacity - src_load * dst_capacity);
1547 
1548         orig_src_load = env->src_stats.load;
1549         orig_dst_load = env->dst_stats.load;
1550 
1551         old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
1552 
1553         /* Would this change make things worse? */
1554         return (imb > old_imb);
1555 }
1556 
1557 /*
1558  * Maximum NUMA importance can be 1998 (2*999);
1559  * SMALLIMP @ 30 would be close to 1998/64.
1560  * Used to deter task migration.
1561  */
1562 #define SMALLIMP        30
1563 
1564 /*
1565  * This checks if the overall compute and NUMA accesses of the system would
1566  * be improved if the source tasks was migrated to the target dst_cpu taking
1567  * into account that it might be best if task running on the dst_cpu should
1568  * be exchanged with the source task
1569  */
1570 static void task_numa_compare(struct task_numa_env *env,
1571                               long taskimp, long groupimp, bool maymove)
1572 {
1573         struct rq *dst_rq = cpu_rq(env->dst_cpu);
1574         struct task_struct *cur;
1575         long src_load, dst_load;
1576         long load;
1577         long imp = env->p->numa_group ? groupimp : taskimp;
1578         long moveimp = imp;
1579         int dist = env->dist;
1580 
1581         if (READ_ONCE(dst_rq->numa_migrate_on))
1582                 return;
1583 
1584         rcu_read_lock();
1585         cur = task_rcu_dereference(&dst_rq->curr);
1586         if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
1587                 cur = NULL;
1588 
1589         /*
1590          * Because we have preemption enabled we can get migrated around and
1591          * end try selecting ourselves (current == env->p) as a swap candidate.
1592          */
1593         if (cur == env->p)
1594                 goto unlock;
1595 
1596         if (!cur) {
1597                 if (maymove && moveimp >= env->best_imp)
1598                         goto assign;
1599                 else
1600                         goto unlock;
1601         }
1602 
1603         /*
1604          * "imp" is the fault differential for the source task between the
1605          * source and destination node. Calculate the total differential for
1606          * the source task and potential destination task. The more negative
1607          * the value is, the more remote accesses that would be expected to
1608          * be incurred if the tasks were swapped.
1609          */
1610         /* Skip this swap candidate if cannot move to the source cpu */
1611         if (!cpumask_test_cpu(env->src_cpu, &cur->cpus_allowed))
1612                 goto unlock;
1613 
1614         /*
1615          * If dst and source tasks are in the same NUMA group, or not
1616          * in any group then look only at task weights.
1617          */
1618         if (cur->numa_group == env->p->numa_group) {
1619                 imp = taskimp + task_weight(cur, env->src_nid, dist) -
1620                       task_weight(cur, env->dst_nid, dist);
1621                 /*
1622                  * Add some hysteresis to prevent swapping the
1623                  * tasks within a group over tiny differences.
1624                  */
1625                 if (cur->numa_group)
1626                         imp -= imp / 16;
1627         } else {
1628                 /*
1629                  * Compare the group weights. If a task is all by itself
1630                  * (not part of a group), use the task weight instead.
1631                  */
1632                 if (cur->numa_group && env->p->numa_group)
1633                         imp += group_weight(cur, env->src_nid, dist) -
1634                                group_weight(cur, env->dst_nid, dist);
1635                 else
1636                         imp += task_weight(cur, env->src_nid, dist) -
1637                                task_weight(cur, env->dst_nid, dist);
1638         }
1639 
1640         if (maymove && moveimp > imp && moveimp > env->best_imp) {
1641                 imp = moveimp;
1642                 cur = NULL;
1643                 goto assign;
1644         }
1645 
1646         /*
1647          * If the NUMA importance is less than SMALLIMP,
1648          * task migration might only result in ping pong
1649          * of tasks and also hurt performance due to cache
1650          * misses.
1651          */
1652         if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
1653                 goto unlock;
1654 
1655         /*
1656          * In the overloaded case, try and keep the load balanced.
1657          */
1658         load = task_h_load(env->p) - task_h_load(cur);
1659         if (!load)
1660                 goto assign;
1661 
1662         dst_load = env->dst_stats.load + load;
1663         src_load = env->src_stats.load - load;
1664 
1665         if (load_too_imbalanced(src_load, dst_load, env))
1666                 goto unlock;
1667 
1668 assign:
1669         /*
1670          * One idle CPU per node is evaluated for a task numa move.
1671          * Call select_idle_sibling to maybe find a better one.
1672          */
1673         if (!cur) {
1674                 /*
1675                  * select_idle_siblings() uses an per-CPU cpumask that
1676                  * can be used from IRQ context.
1677                  */
1678                 local_irq_disable();
1679                 env->dst_cpu = select_idle_sibling(env->p, env->src_cpu,
1680                                                    env->dst_cpu);
1681                 local_irq_enable();
1682         }
1683 
1684         task_numa_assign(env, cur, imp);
1685 unlock:
1686         rcu_read_unlock();
1687 }
1688 
1689 static void task_numa_find_cpu(struct task_numa_env *env,
1690                                 long taskimp, long groupimp)
1691 {
1692         long src_load, dst_load, load;
1693         bool maymove = false;
1694         int cpu;
1695 
1696         load = task_h_load(env->p);
1697         dst_load = env->dst_stats.load + load;
1698         src_load = env->src_stats.load - load;
1699 
1700         /*
1701          * If the improvement from just moving env->p direction is better
1702          * than swapping tasks around, check if a move is possible.
1703          */
1704         maymove = !load_too_imbalanced(src_load, dst_load, env);
1705 
1706         for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
1707                 /* Skip this CPU if the source task cannot migrate */
1708                 if (!cpumask_test_cpu(cpu, &env->p->cpus_allowed))
1709                         continue;
1710 
1711                 env->dst_cpu = cpu;
1712                 task_numa_compare(env, taskimp, groupimp, maymove);
1713         }
1714 }
1715 
1716 static int task_numa_migrate(struct task_struct *p)
1717 {
1718         struct task_numa_env env = {
1719                 .p = p,
1720 
1721                 .src_cpu = task_cpu(p),
1722                 .src_nid = task_node(p),
1723 
1724                 .imbalance_pct = 112,
1725 
1726                 .best_task = NULL,
1727                 .best_imp = 0,
1728                 .best_cpu = -1,
1729         };
1730         struct sched_domain *sd;
1731         struct rq *best_rq;
1732         unsigned long taskweight, groupweight;
1733         int nid, ret, dist;
1734         long taskimp, groupimp;
1735 
1736         /*
1737          * Pick the lowest SD_NUMA domain, as that would have the smallest
1738          * imbalance and would be the first to start moving tasks about.
1739          *
1740          * And we want to avoid any moving of tasks about, as that would create
1741          * random movement of tasks -- counter the numa conditions we're trying
1742          * to satisfy here.
1743          */
1744         rcu_read_lock();
1745         sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
1746         if (sd)
1747                 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
1748         rcu_read_unlock();
1749 
1750         /*
1751          * Cpusets can break the scheduler domain tree into smaller
1752          * balance domains, some of which do not cross NUMA boundaries.
1753          * Tasks that are "trapped" in such domains cannot be migrated
1754          * elsewhere, so there is no point in (re)trying.
1755          */
1756         if (unlikely(!sd)) {
1757                 sched_setnuma(p, task_node(p));
1758                 return -EINVAL;
1759         }
1760 
1761         env.dst_nid = p->numa_preferred_nid;
1762         dist = env.dist = node_distance(env.src_nid, env.dst_nid);
1763         taskweight = task_weight(p, env.src_nid, dist);
1764         groupweight = group_weight(p, env.src_nid, dist);
1765         update_numa_stats(&env.src_stats, env.src_nid);
1766         taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
1767         groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
1768         update_numa_stats(&env.dst_stats, env.dst_nid);
1769 
1770         /* Try to find a spot on the preferred nid. */
1771         task_numa_find_cpu(&env, taskimp, groupimp);
1772 
1773         /*
1774          * Look at other nodes in these cases:
1775          * - there is no space available on the preferred_nid
1776          * - the task is part of a numa_group that is interleaved across
1777          *   multiple NUMA nodes; in order to better consolidate the group,
1778          *   we need to check other locations.
1779          */
1780         if (env.best_cpu == -1 || (p->numa_group && p->numa_group->active_nodes > 1)) {
1781                 for_each_online_node(nid) {
1782                         if (nid == env.src_nid || nid == p->numa_preferred_nid)
1783                                 continue;
1784 
1785                         dist = node_distance(env.src_nid, env.dst_nid);
1786                         if (sched_numa_topology_type == NUMA_BACKPLANE &&
1787                                                 dist != env.dist) {
1788                                 taskweight = task_weight(p, env.src_nid, dist);
1789                                 groupweight = group_weight(p, env.src_nid, dist);
1790                         }
1791 
1792                         /* Only consider nodes where both task and groups benefit */
1793                         taskimp = task_weight(p, nid, dist) - taskweight;
1794                         groupimp = group_weight(p, nid, dist) - groupweight;
1795                         if (taskimp < 0 && groupimp < 0)
1796                                 continue;
1797 
1798                         env.dist = dist;
1799                         env.dst_nid = nid;
1800                         update_numa_stats(&env.dst_stats, env.dst_nid);
1801                         task_numa_find_cpu(&env, taskimp, groupimp);
1802                 }
1803         }
1804 
1805         /*
1806          * If the task is part of a workload that spans multiple NUMA nodes,
1807          * and is migrating into one of the workload's active nodes, remember
1808          * this node as the task's preferred numa node, so the workload can
1809          * settle down.
1810          * A task that migrated to a second choice node will be better off
1811          * trying for a better one later. Do not set the preferred node here.
1812          */
1813         if (p->numa_group) {
1814                 if (env.best_cpu == -1)
1815                         nid = env.src_nid;
1816                 else
1817                         nid = cpu_to_node(env.best_cpu);
1818 
1819                 if (nid != p->numa_preferred_nid)
1820                         sched_setnuma(p, nid);
1821         }
1822 
1823         /* No better CPU than the current one was found. */
1824         if (env.best_cpu == -1)
1825                 return -EAGAIN;
1826 
1827         best_rq = cpu_rq(env.best_cpu);
1828         if (env.best_task == NULL) {
1829                 ret = migrate_task_to(p, env.best_cpu);
1830                 WRITE_ONCE(best_rq->numa_migrate_on, 0);
1831                 if (ret != 0)
1832                         trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
1833                 return ret;
1834         }
1835 
1836         ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
1837         WRITE_ONCE(best_rq->numa_migrate_on, 0);
1838 
1839         if (ret != 0)
1840                 trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
1841         put_task_struct(env.best_task);
1842         return ret;
1843 }
1844 
1845 /* Attempt to migrate a task to a CPU on the preferred node. */
1846 static void numa_migrate_preferred(struct task_struct *p)
1847 {
1848         unsigned long interval = HZ;
1849 
1850         /* This task has no NUMA fault statistics yet */
1851         if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
1852                 return;
1853 
1854         /* Periodically retry migrating the task to the preferred node */
1855         interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
1856         p->numa_migrate_retry = jiffies + interval;
1857 
1858         /* Success if task is already running on preferred CPU */
1859         if (task_node(p) == p->numa_preferred_nid)
1860                 return;
1861 
1862         /* Otherwise, try migrate to a CPU on the preferred node */
1863         task_numa_migrate(p);
1864 }
1865 
1866 /*
1867  * Find out how many nodes on the workload is actively running on. Do this by
1868  * tracking the nodes from which NUMA hinting faults are triggered. This can
1869  * be different from the set of nodes where the workload's memory is currently
1870  * located.
1871  */
1872 static void numa_group_count_active_nodes(struct numa_group *numa_group)
1873 {
1874         unsigned long faults, max_faults = 0;
1875         int nid, active_nodes = 0;
1876 
1877         for_each_online_node(nid) {
1878                 faults = group_faults_cpu(numa_group, nid);
1879                 if (faults > max_faults)
1880                         max_faults = faults;
1881         }
1882 
1883         for_each_online_node(nid) {
1884                 faults = group_faults_cpu(numa_group, nid);
1885                 if (faults * ACTIVE_NODE_FRACTION > max_faults)
1886                         active_nodes++;
1887         }
1888 
1889         numa_group->max_faults_cpu = max_faults;
1890         numa_group->active_nodes = active_nodes;
1891 }
1892 
1893 /*
1894  * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1895  * increments. The more local the fault statistics are, the higher the scan
1896  * period will be for the next scan window. If local/(local+remote) ratio is
1897  * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
1898  * the scan period will decrease. Aim for 70% local accesses.
1899  */
1900 #define NUMA_PERIOD_SLOTS 10
1901 #define NUMA_PERIOD_THRESHOLD 7
1902 
1903 /*
1904  * Increase the scan period (slow down scanning) if the majority of
1905  * our memory is already on our local node, or if the majority of
1906  * the page accesses are shared with other processes.
1907  * Otherwise, decrease the scan period.
1908  */
1909 static void update_task_scan_period(struct task_struct *p,
1910                         unsigned long shared, unsigned long private)
1911 {
1912         unsigned int period_slot;
1913         int lr_ratio, ps_ratio;
1914         int diff;
1915 
1916         unsigned long remote = p->numa_faults_locality[0];
1917         unsigned long local = p->numa_faults_locality[1];
1918 
1919         /*
1920          * If there were no record hinting faults then either the task is
1921          * completely idle or all activity is areas that are not of interest
1922          * to automatic numa balancing. Related to that, if there were failed
1923          * migration then it implies we are migrating too quickly or the local
1924          * node is overloaded. In either case, scan slower
1925          */
1926         if (local + shared == 0 || p->numa_faults_locality[2]) {
1927                 p->numa_scan_period = min(p->numa_scan_period_max,
1928                         p->numa_scan_period << 1);
1929 
1930                 p->mm->numa_next_scan = jiffies +
1931                         msecs_to_jiffies(p->numa_scan_period);
1932 
1933                 return;
1934         }
1935 
1936         /*
1937          * Prepare to scale scan period relative to the current period.
1938          *       == NUMA_PERIOD_THRESHOLD scan period stays the same
1939          *       <  NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1940          *       >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1941          */
1942         period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
1943         lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
1944         ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
1945 
1946         if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
1947                 /*
1948                  * Most memory accesses are local. There is no need to
1949                  * do fast NUMA scanning, since memory is already local.
1950                  */
1951                 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
1952                 if (!slot)
1953                         slot = 1;
1954                 diff = slot * period_slot;
1955         } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
1956                 /*
1957                  * Most memory accesses are shared with other tasks.
1958                  * There is no point in continuing fast NUMA scanning,
1959                  * since other tasks may just move the memory elsewhere.
1960                  */
1961                 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
1962                 if (!slot)
1963                         slot = 1;
1964                 diff = slot * period_slot;
1965         } else {
1966                 /*
1967                  * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
1968                  * yet they are not on the local NUMA node. Speed up
1969                  * NUMA scanning to get the memory moved over.
1970                  */
1971                 int ratio = max(lr_ratio, ps_ratio);
1972                 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
1973         }
1974 
1975         p->numa_scan_period = clamp(p->numa_scan_period + diff,
1976                         task_scan_min(p), task_scan_max(p));
1977         memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
1978 }
1979 
1980 /*
1981  * Get the fraction of time the task has been running since the last
1982  * NUMA placement cycle. The scheduler keeps similar statistics, but
1983  * decays those on a 32ms period, which is orders of magnitude off
1984  * from the dozens-of-seconds NUMA balancing period. Use the scheduler
1985  * stats only if the task is so new there are no NUMA statistics yet.
1986  */
1987 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
1988 {
1989         u64 runtime, delta, now;
1990         /* Use the start of this time slice to avoid calculations. */
1991         now = p->se.exec_start;
1992         runtime = p->se.sum_exec_runtime;
1993 
1994         if (p->last_task_numa_placement) {
1995                 delta = runtime - p->last_sum_exec_runtime;
1996                 *period = now - p->last_task_numa_placement;
1997 
1998                 /* Avoid time going backwards, prevent potential divide error: */
1999                 if (unlikely((s64)*period < 0))
2000                         *period = 0;
2001         } else {
2002                 delta = p->se.avg.load_sum;
2003                 *period = LOAD_AVG_MAX;
2004         }
2005 
2006         p->last_sum_exec_runtime = runtime;
2007         p->last_task_numa_placement = now;
2008 
2009         return delta;
2010 }
2011 
2012 /*
2013  * Determine the preferred nid for a task in a numa_group. This needs to
2014  * be done in a way that produces consistent results with group_weight,
2015  * otherwise workloads might not converge.
2016  */
2017 static int preferred_group_nid(struct task_struct *p, int nid)
2018 {
2019         nodemask_t nodes;
2020         int dist;
2021 
2022         /* Direct connections between all NUMA nodes. */
2023         if (sched_numa_topology_type == NUMA_DIRECT)
2024                 return nid;
2025 
2026         /*
2027          * On a system with glueless mesh NUMA topology, group_weight
2028          * scores nodes according to the number of NUMA hinting faults on
2029          * both the node itself, and on nearby nodes.
2030          */
2031         if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2032                 unsigned long score, max_score = 0;
2033                 int node, max_node = nid;
2034 
2035                 dist = sched_max_numa_distance;
2036 
2037                 for_each_online_node(node) {
2038                         score = group_weight(p, node, dist);
2039                         if (score > max_score) {
2040                                 max_score = score;
2041                                 max_node = node;
2042                         }
2043                 }
2044                 return max_node;
2045         }
2046 
2047         /*
2048          * Finding the preferred nid in a system with NUMA backplane
2049          * interconnect topology is more involved. The goal is to locate
2050          * tasks from numa_groups near each other in the system, and
2051          * untangle workloads from different sides of the system. This requires
2052          * searching down the hierarchy of node groups, recursively searching
2053          * inside the highest scoring group of nodes. The nodemask tricks
2054          * keep the complexity of the search down.
2055          */
2056         nodes = node_online_map;
2057         for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2058                 unsigned long max_faults = 0;
2059                 nodemask_t max_group = NODE_MASK_NONE;
2060                 int a, b;
2061 
2062                 /* Are there nodes at this distance from each other? */
2063                 if (!find_numa_distance(dist))
2064                         continue;
2065 
2066                 for_each_node_mask(a, nodes) {
2067                         unsigned long faults = 0;
2068                         nodemask_t this_group;
2069                         nodes_clear(this_group);
2070 
2071                         /* Sum group's NUMA faults; includes a==b case. */
2072                         for_each_node_mask(b, nodes) {
2073                                 if (node_distance(a, b) < dist) {
2074                                         faults += group_faults(p, b);
2075                                         node_set(b, this_group);
2076                                         node_clear(b, nodes);
2077                                 }
2078                         }
2079 
2080                         /* Remember the top group. */
2081                         if (faults > max_faults) {
2082                                 max_faults = faults;
2083                                 max_group = this_group;
2084                                 /*
2085                                  * subtle: at the smallest distance there is
2086                                  * just one node left in each "group", the
2087                                  * winner is the preferred nid.
2088                                  */
2089                                 nid = a;
2090                         }
2091                 }
2092                 /* Next round, evaluate the nodes within max_group. */
2093                 if (!max_faults)
2094                         break;
2095                 nodes = max_group;
2096         }
2097         return nid;
2098 }
2099 
2100 static void task_numa_placement(struct task_struct *p)
2101 {
2102         int seq, nid, max_nid = -1;
2103         unsigned long max_faults = 0;
2104         unsigned long fault_types[2] = { 0, 0 };
2105         unsigned long total_faults;
2106         u64 runtime, period;
2107         spinlock_t *group_lock = NULL;
2108 
2109         /*
2110          * The p->mm->numa_scan_seq field gets updated without
2111          * exclusive access. Use READ_ONCE() here to ensure
2112          * that the field is read in a single access:
2113          */
2114         seq = READ_ONCE(p->mm->numa_scan_seq);
2115         if (p->numa_scan_seq == seq)
2116                 return;
2117         p->numa_scan_seq = seq;
2118         p->numa_scan_period_max = task_scan_max(p);
2119 
2120         total_faults = p->numa_faults_locality[0] +
2121                        p->numa_faults_locality[1];
2122         runtime = numa_get_avg_runtime(p, &period);
2123 
2124         /* If the task is part of a group prevent parallel updates to group stats */
2125         if (p->numa_group) {
2126                 group_lock = &p->numa_group->lock;
2127                 spin_lock_irq(group_lock);
2128         }
2129 
2130         /* Find the node with the highest number of faults */
2131         for_each_online_node(nid) {
2132                 /* Keep track of the offsets in numa_faults array */
2133                 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2134                 unsigned long faults = 0, group_faults = 0;
2135                 int priv;
2136 
2137                 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2138                         long diff, f_diff, f_weight;
2139 
2140                         mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2141                         membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2142                         cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2143                         cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2144 
2145                         /* Decay existing window, copy faults since last scan */
2146                         diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2147                         fault_types[priv] += p->numa_faults[membuf_idx];
2148                         p->numa_faults[membuf_idx] = 0;
2149 
2150                         /*
2151                          * Normalize the faults_from, so all tasks in a group
2152                          * count according to CPU use, instead of by the raw
2153                          * number of faults. Tasks with little runtime have
2154                          * little over-all impact on throughput, and thus their
2155                          * faults are less important.
2156                          */
2157                         f_weight = div64_u64(runtime << 16, period + 1);
2158                         f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2159                                    (total_faults + 1);
2160                         f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2161                         p->numa_faults[cpubuf_idx] = 0;
2162 
2163                         p->numa_faults[mem_idx] += diff;
2164                         p->numa_faults[cpu_idx] += f_diff;
2165                         faults += p->numa_faults[mem_idx];
2166                         p->total_numa_faults += diff;
2167                         if (p->numa_group) {
2168                                 /*
2169                                  * safe because we can only change our own group
2170                                  *
2171                                  * mem_idx represents the offset for a given
2172                                  * nid and priv in a specific region because it
2173                                  * is at the beginning of the numa_faults array.
2174                                  */
2175                                 p->numa_group->faults[mem_idx] += diff;
2176                                 p->numa_group->faults_cpu[mem_idx] += f_diff;
2177                                 p->numa_group->total_faults += diff;
2178                                 group_faults += p->numa_group->faults[mem_idx];
2179                         }
2180                 }
2181 
2182                 if (!p->numa_group) {
2183                         if (faults > max_faults) {
2184                                 max_faults = faults;
2185                                 max_nid = nid;
2186                         }
2187                 } else if (group_faults > max_faults) {
2188                         max_faults = group_faults;
2189                         max_nid = nid;
2190                 }
2191         }
2192 
2193         if (p->numa_group) {
2194                 numa_group_count_active_nodes(p->numa_group);
2195                 spin_unlock_irq(group_lock);
2196                 max_nid = preferred_group_nid(p, max_nid);
2197         }
2198 
2199         if (max_faults) {
2200                 /* Set the new preferred node */
2201                 if (max_nid != p->numa_preferred_nid)
2202                         sched_setnuma(p, max_nid);
2203         }
2204 
2205         update_task_scan_period(p, fault_types[0], fault_types[1]);
2206 }
2207 
2208 static inline int get_numa_group(struct numa_group *grp)
2209 {
2210         return atomic_inc_not_zero(&grp->refcount);
2211 }
2212 
2213 static inline void put_numa_group(struct numa_group *grp)
2214 {
2215         if (atomic_dec_and_test(&grp->refcount))
2216                 kfree_rcu(grp, rcu);
2217 }
2218 
2219 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2220                         int *priv)
2221 {
2222         struct numa_group *grp, *my_grp;
2223         struct task_struct *tsk;
2224         bool join = false;
2225         int cpu = cpupid_to_cpu(cpupid);
2226         int i;
2227 
2228         if (unlikely(!p->numa_group)) {
2229                 unsigned int size = sizeof(struct numa_group) +
2230                                     4*nr_node_ids*sizeof(unsigned long);
2231 
2232                 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2233                 if (!grp)
2234                         return;
2235 
2236                 atomic_set(&grp->refcount, 1);
2237                 grp->active_nodes = 1;
2238                 grp->max_faults_cpu = 0;
2239                 spin_lock_init(&grp->lock);
2240                 grp->gid = p->pid;
2241                 /* Second half of the array tracks nids where faults happen */
2242                 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
2243                                                 nr_node_ids;
2244 
2245                 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2246                         grp->faults[i] = p->numa_faults[i];
2247 
2248                 grp->total_faults = p->total_numa_faults;
2249 
2250                 grp->nr_tasks++;
2251                 rcu_assign_pointer(p->numa_group, grp);
2252         }
2253 
2254         rcu_read_lock();
2255         tsk = READ_ONCE(cpu_rq(cpu)->curr);
2256 
2257         if (!cpupid_match_pid(tsk, cpupid))
2258                 goto no_join;
2259 
2260         grp = rcu_dereference(tsk->numa_group);
2261         if (!grp)
2262                 goto no_join;
2263 
2264         my_grp = p->numa_group;
2265         if (grp == my_grp)
2266                 goto no_join;
2267 
2268         /*
2269          * Only join the other group if its bigger; if we're the bigger group,
2270          * the other task will join us.
2271          */
2272         if (my_grp->nr_tasks > grp->nr_tasks)
2273                 goto no_join;
2274 
2275         /*
2276          * Tie-break on the grp address.
2277          */
2278         if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
2279                 goto no_join;
2280 
2281         /* Always join threads in the same process. */
2282         if (tsk->mm == current->mm)
2283                 join = true;
2284 
2285         /* Simple filter to avoid false positives due to PID collisions */
2286         if (flags & TNF_SHARED)
2287                 join = true;
2288 
2289         /* Update priv based on whether false sharing was detected */
2290         *priv = !join;
2291 
2292         if (join && !get_numa_group(grp))
2293                 goto no_join;
2294 
2295         rcu_read_unlock();
2296 
2297         if (!join)
2298                 return;
2299 
2300         BUG_ON(irqs_disabled());
2301         double_lock_irq(&my_grp->lock, &grp->lock);
2302 
2303         for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
2304                 my_grp->faults[i] -= p->numa_faults[i];
2305                 grp->faults[i] += p->numa_faults[i];
2306         }
2307         my_grp->total_faults -= p->total_numa_faults;
2308         grp->total_faults += p->total_numa_faults;
2309 
2310         my_grp->nr_tasks--;
2311         grp->nr_tasks++;
2312 
2313         spin_unlock(&my_grp->lock);
2314         spin_unlock_irq(&grp->lock);
2315 
2316         rcu_assign_pointer(p->numa_group, grp);
2317 
2318         put_numa_group(my_grp);
2319         return;
2320 
2321 no_join:
2322         rcu_read_unlock();
2323         return;
2324 }
2325 
2326 void task_numa_free(struct task_struct *p)
2327 {
2328         struct numa_group *grp = p->numa_group;
2329         void *numa_faults = p->numa_faults;
2330         unsigned long flags;
2331         int i;
2332 
2333         if (grp) {
2334                 spin_lock_irqsave(&grp->lock, flags);
2335                 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2336                         grp->faults[i] -= p->numa_faults[i];
2337                 grp->total_faults -= p->total_numa_faults;
2338 
2339                 grp->nr_tasks--;
2340                 spin_unlock_irqrestore(&grp->lock, flags);
2341                 RCU_INIT_POINTER(p->numa_group, NULL);
2342                 put_numa_group(grp);
2343         }
2344 
2345         p->numa_faults = NULL;
2346         kfree(numa_faults);
2347 }
2348 
2349 /*
2350  * Got a PROT_NONE fault for a page on @node.
2351  */
2352 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
2353 {
2354         struct task_struct *p = current;
2355         bool migrated = flags & TNF_MIGRATED;
2356         int cpu_node = task_node(current);
2357         int local = !!(flags & TNF_FAULT_LOCAL);
2358         struct numa_group *ng;
2359         int priv;
2360 
2361         if (!static_branch_likely(&sched_numa_balancing))
2362                 return;
2363 
2364         /* for example, ksmd faulting in a user's mm */
2365         if (!p->mm)
2366                 return;
2367 
2368         /* Allocate buffer to track faults on a per-node basis */
2369         if (unlikely(!p->numa_faults)) {
2370                 int size = sizeof(*p->numa_faults) *
2371                            NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
2372 
2373                 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
2374                 if (!p->numa_faults)
2375                         return;
2376 
2377                 p->total_numa_faults = 0;
2378                 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2379         }
2380 
2381         /*
2382          * First accesses are treated as private, otherwise consider accesses
2383          * to be private if the accessing pid has not changed
2384          */
2385         if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
2386                 priv = 1;
2387         } else {
2388                 priv = cpupid_match_pid(p, last_cpupid);
2389                 if (!priv && !(flags & TNF_NO_GROUP))
2390                         task_numa_group(p, last_cpupid, flags, &priv);
2391         }
2392 
2393         /*
2394          * If a workload spans multiple NUMA nodes, a shared fault that
2395          * occurs wholly within the set of nodes that the workload is
2396          * actively using should be counted as local. This allows the
2397          * scan rate to slow down when a workload has settled down.
2398          */
2399         ng = p->numa_group;
2400         if (!priv && !local && ng && ng->active_nodes > 1 &&
2401                                 numa_is_active_node(cpu_node, ng) &&
2402                                 numa_is_active_node(mem_node, ng))
2403                 local = 1;
2404 
2405         /*
2406          * Retry to migrate task to preferred node periodically, in case it
2407          * previously failed, or the scheduler moved us.
2408          */
2409         if (time_after(jiffies, p->numa_migrate_retry)) {
2410                 task_numa_placement(p);
2411                 numa_migrate_preferred(p);
2412         }
2413 
2414         if (migrated)
2415                 p->numa_pages_migrated += pages;
2416         if (flags & TNF_MIGRATE_FAIL)
2417                 p->numa_faults_locality[2] += pages;
2418 
2419         p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
2420         p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
2421         p->numa_faults_locality[local] += pages;
2422 }
2423 
2424 static void reset_ptenuma_scan(struct task_struct *p)
2425 {
2426         /*
2427          * We only did a read acquisition of the mmap sem, so
2428          * p->mm->numa_scan_seq is written to without exclusive access
2429          * and the update is not guaranteed to be atomic. That's not
2430          * much of an issue though, since this is just used for
2431          * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
2432          * expensive, to avoid any form of compiler optimizations:
2433          */
2434         WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
2435         p->mm->numa_scan_offset = 0;
2436 }
2437 
2438 /*
2439  * The expensive part of numa migration is done from task_work context.
2440  * Triggered from task_tick_numa().
2441  */
2442 void task_numa_work(struct callback_head *work)
2443 {
2444         unsigned long migrate, next_scan, now = jiffies;
2445         struct task_struct *p = current;
2446         struct mm_struct *mm = p->mm;
2447         u64 runtime = p->se.sum_exec_runtime;
2448         struct vm_area_struct *vma;
2449         unsigned long start, end;
2450         unsigned long nr_pte_updates = 0;
2451         long pages, virtpages;
2452 
2453         SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
2454 
2455         work->next = work; /* protect against double add */
2456         /*
2457          * Who cares about NUMA placement when they're dying.
2458          *
2459          * NOTE: make sure not to dereference p->mm before this check,
2460          * exit_task_work() happens _after_ exit_mm() so we could be called
2461          * without p->mm even though we still had it when we enqueued this
2462          * work.
2463          */
2464         if (p->flags & PF_EXITING)
2465                 return;
2466 
2467         if (!mm->numa_next_scan) {
2468                 mm->numa_next_scan = now +
2469                         msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2470         }
2471 
2472         /*
2473          * Enforce maximal scan/migration frequency..
2474          */
2475         migrate = mm->numa_next_scan;
2476         if (time_before(now, migrate))
2477                 return;
2478 
2479         if (p->numa_scan_period == 0) {
2480                 p->numa_scan_period_max = task_scan_max(p);
2481                 p->numa_scan_period = task_scan_start(p);
2482         }
2483 
2484         next_scan = now + msecs_to_jiffies(p->numa_scan_period);
2485         if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
2486                 return;
2487 
2488         /*
2489          * Delay this task enough that another task of this mm will likely win
2490          * the next time around.
2491          */
2492         p->node_stamp += 2 * TICK_NSEC;
2493 
2494         start = mm->numa_scan_offset;
2495         pages = sysctl_numa_balancing_scan_size;
2496         pages <<= 20 - PAGE_SHIFT; /* MB in pages */
2497         virtpages = pages * 8;     /* Scan up to this much virtual space */
2498         if (!pages)
2499                 return;
2500 
2501 
2502         if (!down_read_trylock(&mm->mmap_sem))
2503                 return;
2504         vma = find_vma(mm, start);
2505         if (!vma) {
2506                 reset_ptenuma_scan(p);
2507                 start = 0;
2508                 vma = mm->mmap;
2509         }
2510         for (; vma; vma = vma->vm_next) {
2511                 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
2512                         is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
2513                         continue;
2514                 }
2515 
2516                 /*
2517                  * Shared library pages mapped by multiple processes are not
2518                  * migrated as it is expected they are cache replicated. Avoid
2519                  * hinting faults in read-only file-backed mappings or the vdso
2520                  * as migrating the pages will be of marginal benefit.
2521                  */
2522                 if (!vma->vm_mm ||
2523                     (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
2524                         continue;
2525 
2526                 /*
2527                  * Skip inaccessible VMAs to avoid any confusion between
2528                  * PROT_NONE and NUMA hinting ptes
2529                  */
2530                 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
2531                         continue;
2532 
2533                 do {
2534                         start = max(start, vma->vm_start);
2535                         end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
2536                         end = min(end, vma->vm_end);
2537                         nr_pte_updates = change_prot_numa(vma, start, end);
2538 
2539                         /*
2540                          * Try to scan sysctl_numa_balancing_size worth of
2541                          * hpages that have at least one present PTE that
2542                          * is not already pte-numa. If the VMA contains
2543                          * areas that are unused or already full of prot_numa
2544                          * PTEs, scan up to virtpages, to skip through those
2545                          * areas faster.
2546                          */
2547                         if (nr_pte_updates)
2548                                 pages -= (end - start) >> PAGE_SHIFT;
2549                         virtpages -= (end - start) >> PAGE_SHIFT;
2550 
2551                         start = end;
2552                         if (pages <= 0 || virtpages <= 0)
2553                                 goto out;
2554 
2555                         cond_resched();
2556                 } while (end != vma->vm_end);
2557         }
2558 
2559 out:
2560         /*
2561          * It is possible to reach the end of the VMA list but the last few
2562          * VMAs are not guaranteed to the vma_migratable. If they are not, we
2563          * would find the !migratable VMA on the next scan but not reset the
2564          * scanner to the start so check it now.
2565          */
2566         if (vma)
2567                 mm->numa_scan_offset = start;
2568         else
2569                 reset_ptenuma_scan(p);
2570         up_read(&mm->mmap_sem);
2571 
2572         /*
2573          * Make sure tasks use at least 32x as much time to run other code
2574          * than they used here, to limit NUMA PTE scanning overhead to 3% max.
2575          * Usually update_task_scan_period slows down scanning enough; on an
2576          * overloaded system we need to limit overhead on a per task basis.
2577          */
2578         if (unlikely(p->se.sum_exec_runtime != runtime)) {
2579                 u64 diff = p->se.sum_exec_runtime - runtime;
2580                 p->node_stamp += 32 * diff;
2581         }
2582 }
2583 
2584 /*
2585  * Drive the periodic memory faults..
2586  */
2587 void task_tick_numa(struct rq *rq, struct task_struct *curr)
2588 {
2589         struct callback_head *work = &curr->numa_work;
2590         u64 period, now;
2591 
2592         /*
2593          * We don't care about NUMA placement if we don't have memory.
2594          */
2595         if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
2596                 return;
2597 
2598         /*
2599          * Using runtime rather than walltime has the dual advantage that
2600          * we (mostly) drive the selection from busy threads and that the
2601          * task needs to have done some actual work before we bother with
2602          * NUMA placement.
2603          */
2604         now = curr->se.sum_exec_runtime;
2605         period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
2606 
2607         if (now > curr->node_stamp + period) {
2608                 if (!curr->node_stamp)
2609                         curr->numa_scan_period = task_scan_start(curr);
2610                 curr->node_stamp += period;
2611 
2612                 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
2613                         init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
2614                         task_work_add(curr, work, true);
2615                 }
2616         }
2617 }
2618 
2619 static void update_scan_period(struct task_struct *p, int new_cpu)
2620 {
2621         int src_nid = cpu_to_node(task_cpu(p));
2622         int dst_nid = cpu_to_node(new_cpu);
2623 
2624         if (!static_branch_likely(&sched_numa_balancing))
2625                 return;
2626 
2627         if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
2628                 return;
2629 
2630         if (src_nid == dst_nid)
2631                 return;
2632 
2633         /*
2634          * Allow resets if faults have been trapped before one scan
2635          * has completed. This is most likely due to a new task that
2636          * is pulled cross-node due to wakeups or load balancing.
2637          */
2638         if (p->numa_scan_seq) {
2639                 /*
2640                  * Avoid scan adjustments if moving to the preferred
2641                  * node or if the task was not previously running on
2642                  * the preferred node.
2643                  */
2644                 if (dst_nid == p->numa_preferred_nid ||
2645                     (p->numa_preferred_nid != -1 && src_nid != p->numa_preferred_nid))
2646                         return;
2647         }
2648 
2649         p->numa_scan_period = task_scan_start(p);
2650 }
2651 
2652 #else
2653 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2654 {
2655 }
2656 
2657 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2658 {
2659 }
2660 
2661 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2662 {
2663 }
2664 
2665 static inline void update_scan_period(struct task_struct *p, int new_cpu)
2666 {
2667 }
2668 
2669 #endif /* CONFIG_NUMA_BALANCING */
2670 
2671 static void
2672 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2673 {
2674         update_load_add(&cfs_rq->load, se->load.weight);
2675         if (!parent_entity(se))
2676                 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
2677 #ifdef CONFIG_SMP
2678         if (entity_is_task(se)) {
2679                 struct rq *rq = rq_of(cfs_rq);
2680 
2681                 account_numa_enqueue(rq, task_of(se));
2682                 list_add(&se->group_node, &rq->cfs_tasks);
2683         }
2684 #endif
2685         cfs_rq->nr_running++;
2686 }
2687 
2688 static void
2689 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2690 {
2691         update_load_sub(&cfs_rq->load, se->load.weight);
2692         if (!parent_entity(se))
2693                 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
2694 #ifdef CONFIG_SMP
2695         if (entity_is_task(se)) {
2696                 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
2697                 list_del_init(&se->group_node);
2698         }
2699 #endif
2700         cfs_rq->nr_running--;
2701 }
2702 
2703 /*
2704  * Signed add and clamp on underflow.
2705  *
2706  * Explicitly do a load-store to ensure the intermediate value never hits
2707  * memory. This allows lockless observations without ever seeing the negative
2708  * values.
2709  */
2710 #define add_positive(_ptr, _val) do {                           \
2711         typeof(_ptr) ptr = (_ptr);                              \
2712         typeof(_val) val = (_val);                              \
2713         typeof(*ptr) res, var = READ_ONCE(*ptr);                \
2714                                                                 \
2715         res = var + val;                                        \
2716                                                                 \
2717         if (val < 0 && res > var)                               \
2718                 res = 0;                                        \
2719                                                                 \
2720         WRITE_ONCE(*ptr, res);                                  \
2721 } while (0)
2722 
2723 /*
2724  * Unsigned subtract and clamp on underflow.
2725  *
2726  * Explicitly do a load-store to ensure the intermediate value never hits
2727  * memory. This allows lockless observations without ever seeing the negative
2728  * values.
2729  */
2730 #define sub_positive(_ptr, _val) do {                           \
2731         typeof(_ptr) ptr = (_ptr);                              \
2732         typeof(*ptr) val = (_val);                              \
2733         typeof(*ptr) res, var = READ_ONCE(*ptr);                \
2734         res = var - val;                                        \
2735         if (res > var)                                          \
2736                 res = 0;                                        \
2737         WRITE_ONCE(*ptr, res);                                  \
2738 } while (0)
2739 
2740 /*
2741  * Remove and clamp on negative, from a local variable.
2742  *
2743  * A variant of sub_positive(), which does not use explicit load-store
2744  * and is thus optimized for local variable updates.
2745  */
2746 #define lsub_positive(_ptr, _val) do {                          \
2747         typeof(_ptr) ptr = (_ptr);                              \
2748         *ptr -= min_t(typeof(*ptr), *ptr, _val);                \
2749 } while (0)
2750 
2751 #ifdef CONFIG_SMP
2752 static inline void
2753 enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
2754 {
2755         cfs_rq->runnable_weight += se->runnable_weight;
2756 
2757         cfs_rq->avg.runnable_load_avg += se->avg.runnable_load_avg;
2758         cfs_rq->avg.runnable_load_sum += se_runnable(se) * se->avg.runnable_load_sum;
2759 }
2760 
2761 static inline void
2762 dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
2763 {
2764         cfs_rq->runnable_weight -= se->runnable_weight;
2765 
2766         sub_positive(&cfs_rq->avg.runnable_load_avg, se->avg.runnable_load_avg);
2767         sub_positive(&cfs_rq->avg.runnable_load_sum,
2768                      se_runnable(se) * se->avg.runnable_load_sum);
2769 }
2770 
2771 static inline void
2772 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
2773 {
2774         cfs_rq->avg.load_avg += se->avg.load_avg;
2775         cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
2776 }
2777 
2778 static inline void
2779 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
2780 {
2781         sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
2782         sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
2783 }
2784 #else
2785 static inline void
2786 enqueue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
2787 static inline void
2788 dequeue_runnable_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
2789 static inline void
2790 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
2791 static inline void
2792 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
2793 #endif
2794 
2795 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
2796                             unsigned long weight, unsigned long runnable)
2797 {
2798         if (se->on_rq) {
2799                 /* commit outstanding execution time */
2800                 if (cfs_rq->curr == se)
2801                         update_curr(cfs_rq);
2802                 account_entity_dequeue(cfs_rq, se);
2803                 dequeue_runnable_load_avg(cfs_rq, se);
2804         }
2805         dequeue_load_avg(cfs_rq, se);
2806 
2807         se->runnable_weight = runnable;
2808         update_load_set(&se->load, weight);
2809 
2810 #ifdef CONFIG_SMP
2811         do {
2812                 u32 divider = LOAD_AVG_MAX - 1024 + se->avg.period_contrib;
2813 
2814                 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
2815                 se->avg.runnable_load_avg =
2816                         div_u64(se_runnable(se) * se->avg.runnable_load_sum, divider);
2817         } while (0);
2818 #endif
2819 
2820         enqueue_load_avg(cfs_rq, se);
2821         if (se->on_rq) {
2822                 account_entity_enqueue(cfs_rq, se);
2823                 enqueue_runnable_load_avg(cfs_rq, se);
2824         }
2825 }
2826 
2827 void reweight_task(struct task_struct *p, int prio)
2828 {
2829         struct sched_entity *se = &p->se;
2830         struct cfs_rq *cfs_rq = cfs_rq_of(se);
2831         struct load_weight *load = &se->load;
2832         unsigned long weight = scale_load(sched_prio_to_weight[prio]);
2833 
2834         reweight_entity(cfs_rq, se, weight, weight);
2835         load->inv_weight = sched_prio_to_wmult[prio];
2836 }
2837 
2838 #ifdef CONFIG_FAIR_GROUP_SCHED
2839 #ifdef CONFIG_SMP
2840 /*
2841  * All this does is approximate the hierarchical proportion which includes that
2842  * global sum we all love to hate.
2843  *
2844  * That is, the weight of a group entity, is the proportional share of the
2845  * group weight based on the group runqueue weights. That is:
2846  *
2847  *                     tg->weight * grq->load.weight
2848  *   ge->load.weight = -----------------------------               (1)
2849  *                        \Sum grq->load.weight
2850  *
2851  * Now, because computing that sum is prohibitively expensive to compute (been
2852  * there, done that) we approximate it with this average stuff. The average
2853  * moves slower and therefore the approximation is cheaper and more stable.
2854  *
2855  * So instead of the above, we substitute:
2856  *
2857  *   grq->load.weight -> grq->avg.load_avg                         (2)
2858  *
2859  * which yields the following:
2860  *
2861  *                     tg->weight * grq->avg.load_avg
2862  *   ge->load.weight = ------------------------------              (3)
2863  *                              tg->load_avg
2864  *
2865  * Where: tg->load_avg ~= \Sum grq->avg.load_avg
2866  *
2867  * That is shares_avg, and it is right (given the approximation (2)).
2868  *
2869  * The problem with it is that because the average is slow -- it was designed
2870  * to be exactly that of course -- this leads to transients in boundary
2871  * conditions. In specific, the case where the group was idle and we start the
2872  * one task. It takes time for our CPU's grq->avg.load_avg to build up,
2873  * yielding bad latency etc..
2874  *
2875  * Now, in that special case (1) reduces to:
2876  *
2877  *                     tg->weight * grq->load.weight
2878  *   ge->load.weight = ----------------------------- = tg->weight   (4)
2879  *                          grp->load.weight
2880  *
2881  * That is, the sum collapses because all other CPUs are idle; the UP scenario.
2882  *
2883  * So what we do is modify our approximation (3) to approach (4) in the (near)
2884  * UP case, like:
2885  *
2886  *   ge->load.weight =
2887  *
2888  *              tg->weight * grq->load.weight
2889  *     ---------------------------------------------------         (5)
2890  *     tg->load_avg - grq->avg.load_avg + grq->load.weight
2891  *
2892  * But because grq->load.weight can drop to 0, resulting in a divide by zero,
2893  * we need to use grq->avg.load_avg as its lower bound, which then gives:
2894  *
2895  *
2896  *                     tg->weight * grq->load.weight
2897  *   ge->load.weight = -----------------------------               (6)
2898  *                              tg_load_avg'
2899  *
2900  * Where:
2901  *
2902  *   tg_load_avg' = tg->load_avg - grq->avg.load_avg +
2903  *                  max(grq->load.weight, grq->avg.load_avg)
2904  *
2905  * And that is shares_weight and is icky. In the (near) UP case it approaches
2906  * (4) while in the normal case it approaches (3). It consistently
2907  * overestimates the ge->load.weight and therefore:
2908  *
2909  *   \Sum ge->load.weight >= tg->weight
2910  *
2911  * hence icky!
2912  */
2913 static long calc_group_shares(struct cfs_rq *cfs_rq)
2914 {
2915         long tg_weight, tg_shares, load, shares;
2916         struct task_group *tg = cfs_rq->tg;
2917 
2918         tg_shares = READ_ONCE(tg->shares);
2919 
2920         load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
2921 
2922         tg_weight = atomic_long_read(&tg->load_avg);
2923 
2924         /* Ensure tg_weight >= load */
2925         tg_weight -= cfs_rq->tg_load_avg_contrib;
2926         tg_weight += load;
2927 
2928         shares = (tg_shares * load);
2929         if (tg_weight)
2930                 shares /= tg_weight;
2931 
2932         /*
2933          * MIN_SHARES has to be unscaled here to support per-CPU partitioning
2934          * of a group with small tg->shares value. It is a floor value which is
2935          * assigned as a minimum load.weight to the sched_entity representing
2936          * the group on a CPU.
2937          *
2938          * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
2939          * on an 8-core system with 8 tasks each runnable on one CPU shares has
2940          * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
2941          * case no task is runnable on a CPU MIN_SHARES=2 should be returned
2942          * instead of 0.
2943          */
2944         return clamp_t(long, shares, MIN_SHARES, tg_shares);
2945 }
2946 
2947 /*
2948  * This calculates the effective runnable weight for a group entity based on
2949  * the group entity weight calculated above.
2950  *
2951  * Because of the above approximation (2), our group entity weight is
2952  * an load_avg based ratio (3). This means that it includes blocked load and
2953  * does not represent the runnable weight.
2954  *
2955  * Approximate the group entity's runnable weight per ratio from the group
2956  * runqueue:
2957  *
2958  *                                           grq->avg.runnable_load_avg
2959  *   ge->runnable_weight = ge->load.weight * -------------------------- (7)
2960  *                                               grq->avg.load_avg
2961  *
2962  * However, analogous to above, since the avg numbers are slow, this leads to
2963  * transients in the from-idle case. Instead we use:
2964  *
2965  *   ge->runnable_weight = ge->load.weight *
2966  *
2967  *              max(grq->avg.runnable_load_avg, grq->runnable_weight)
2968  *              -----------------------------------------------------   (8)
2969  *                    max(grq->avg.load_avg, grq->load.weight)
2970  *
2971  * Where these max() serve both to use the 'instant' values to fix the slow
2972  * from-idle and avoid the /0 on to-idle, similar to (6).
2973  */
2974 static long calc_group_runnable(struct cfs_rq *cfs_rq, long shares)
2975 {
2976         long runnable, load_avg;
2977 
2978         load_avg = max(cfs_rq->avg.load_avg,
2979                        scale_load_down(cfs_rq->load.weight));
2980 
2981         runnable = max(cfs_rq->avg.runnable_load_avg,
2982                        scale_load_down(cfs_rq->runnable_weight));
2983 
2984         runnable *= shares;
2985         if (load_avg)
2986                 runnable /= load_avg;
2987 
2988         return clamp_t(long, runnable, MIN_SHARES, shares);
2989 }
2990 #endif /* CONFIG_SMP */
2991 
2992 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
2993 
2994 /*
2995  * Recomputes the group entity based on the current state of its group
2996  * runqueue.
2997  */
2998 static void update_cfs_group(struct sched_entity *se)
2999 {
3000         struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3001         long shares, runnable;
3002 
3003         if (!gcfs_rq)
3004                 return;
3005 
3006         if (throttled_hierarchy(gcfs_rq))
3007                 return;
3008 
3009 #ifndef CONFIG_SMP
3010         runnable = shares = READ_ONCE(gcfs_rq->tg->shares);
3011 
3012         if (likely(se->load.weight == shares))
3013                 return;
3014 #else
3015         shares   = calc_group_shares(gcfs_rq);
3016         runnable = calc_group_runnable(gcfs_rq, shares);
3017 #endif
3018 
3019         reweight_entity(cfs_rq_of(se), se, shares, runnable);
3020 }
3021 
3022 #else /* CONFIG_FAIR_GROUP_SCHED */
3023 static inline void update_cfs_group(struct sched_entity *se)
3024 {
3025 }
3026 #endif /* CONFIG_FAIR_GROUP_SCHED */
3027 
3028 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3029 {
3030         struct rq *rq = rq_of(cfs_rq);
3031 
3032         if (&rq->cfs == cfs_rq || (flags & SCHED_CPUFREQ_MIGRATION)) {
3033                 /*
3034                  * There are a few boundary cases this might miss but it should
3035                  * get called often enough that that should (hopefully) not be
3036                  * a real problem.
3037                  *
3038                  * It will not get called when we go idle, because the idle
3039                  * thread is a different class (!fair), nor will the utilization
3040                  * number include things like RT tasks.
3041                  *
3042                  * As is, the util number is not freq-invariant (we'd have to
3043                  * implement arch_scale_freq_capacity() for that).
3044                  *
3045                  * See cpu_util().
3046                  */
3047                 cpufreq_update_util(rq, flags);
3048         }
3049 }
3050 
3051 #ifdef CONFIG_SMP
3052 #ifdef CONFIG_FAIR_GROUP_SCHED
3053 /**
3054  * update_tg_load_avg - update the tg's load avg
3055  * @cfs_rq: the cfs_rq whose avg changed
3056  * @force: update regardless of how small the difference
3057  *
3058  * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
3059  * However, because tg->load_avg is a global value there are performance
3060  * considerations.
3061  *
3062  * In order to avoid having to look at the other cfs_rq's, we use a
3063  * differential update where we store the last value we propagated. This in
3064  * turn allows skipping updates if the differential is 'small'.
3065  *
3066  * Updating tg's load_avg is necessary before update_cfs_share().
3067  */
3068 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force)
3069 {
3070         long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
3071 
3072         /*
3073          * No need to update load_avg for root_task_group as it is not used.
3074          */
3075         if (cfs_rq->tg == &root_task_group)
3076                 return;
3077 
3078         if (force || abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
3079                 atomic_long_add(delta, &cfs_rq->tg->load_avg);
3080                 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
3081         }
3082 }
3083 
3084 /*
3085  * Called within set_task_rq() right before setting a task's CPU. The
3086  * caller only guarantees p->pi_lock is held; no other assumptions,
3087  * including the state of rq->lock, should be made.
3088  */
3089 void set_task_rq_fair(struct sched_entity *se,
3090                       struct cfs_rq *prev, struct cfs_rq *next)
3091 {
3092         u64 p_last_update_time;
3093         u64 n_last_update_time;
3094 
3095         if (!sched_feat(ATTACH_AGE_LOAD))
3096                 return;
3097 
3098         /*
3099          * We are supposed to update the task to "current" time, then its up to
3100          * date and ready to go to new CPU/cfs_rq. But we have difficulty in
3101          * getting what current time is, so simply throw away the out-of-date
3102          * time. This will result in the wakee task is less decayed, but giving
3103          * the wakee more load sounds not bad.
3104          */
3105         if (!(se->avg.last_update_time && prev))
3106                 return;
3107 
3108 #ifndef CONFIG_64BIT
3109         {
3110                 u64 p_last_update_time_copy;
3111                 u64 n_last_update_time_copy;
3112 
3113                 do {
3114                         p_last_update_time_copy = prev->load_last_update_time_copy;
3115                         n_last_update_time_copy = next->load_last_update_time_copy;
3116 
3117                         smp_rmb();
3118 
3119                         p_last_update_time = prev->avg.last_update_time;
3120                         n_last_update_time = next->avg.last_update_time;
3121 
3122                 } while (p_last_update_time != p_last_update_time_copy ||
3123                          n_last_update_time != n_last_update_time_copy);
3124         }
3125 #else
3126         p_last_update_time = prev->avg.last_update_time;
3127         n_last_update_time = next->avg.last_update_time;
3128 #endif
3129         __update_load_avg_blocked_se(p_last_update_time, cpu_of(rq_of(prev)), se);
3130         se->avg.last_update_time = n_last_update_time;
3131 }
3132 
3133 
3134 /*
3135  * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
3136  * propagate its contribution. The key to this propagation is the invariant
3137  * that for each group:
3138  *
3139  *   ge->avg == grq->avg                                                (1)
3140  *
3141  * _IFF_ we look at the pure running and runnable sums. Because they
3142  * represent the very same entity, just at different points in the hierarchy.
3143  *
3144  * Per the above update_tg_cfs_util() is trivial and simply copies the running
3145  * sum over (but still wrong, because the group entity and group rq do not have
3146  * their PELT windows aligned).
3147  *
3148  * However, update_tg_cfs_runnable() is more complex. So we have:
3149  *
3150  *   ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg          (2)
3151  *
3152  * And since, like util, the runnable part should be directly transferable,
3153  * the following would _appear_ to be the straight forward approach:
3154  *
3155  *   grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg       (3)
3156  *
3157  * And per (1) we have:
3158  *
3159  *   ge->avg.runnable_avg == grq->avg.runnable_avg
3160  *
3161  * Which gives:
3162  *
3163  *                      ge->load.weight * grq->avg.load_avg
3164  *   ge->avg.load_avg = -----------------------------------             (4)
3165  *                               grq->load.weight
3166  *
3167  * Except that is wrong!
3168  *
3169  * Because while for entities historical weight is not important and we
3170  * really only care about our future and therefore can consider a pure
3171  * runnable sum, runqueues can NOT do this.
3172  *
3173  * We specifically want runqueues to have a load_avg that includes
3174  * historical weights. Those represent the blocked load, the load we expect
3175  * to (shortly) return to us. This only works by keeping the weights as
3176  * integral part of the sum. We therefore cannot decompose as per (3).
3177  *
3178  * Another reason this doesn't work is that runnable isn't a 0-sum entity.
3179  * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
3180  * rq itself is runnable anywhere between 2/3 and 1 depending on how the
3181  * runnable section of these tasks overlap (or not). If they were to perfectly
3182  * align the rq as a whole would be runnable 2/3 of the time. If however we
3183  * always have at least 1 runnable task, the rq as a whole is always runnable.
3184  *
3185  * So we'll have to approximate.. :/
3186  *
3187  * Given the constraint:
3188  *
3189  *   ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
3190  *
3191  * We can construct a rule that adds runnable to a rq by assuming minimal
3192  * overlap.
3193  *
3194  * On removal, we'll assume each task is equally runnable; which yields:
3195  *
3196  *   grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
3197  *
3198  * XXX: only do this for the part of runnable > running ?
3199  *
3200  */
3201 
3202 static inline void
3203 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3204 {
3205         long delta = gcfs_rq->avg.util_avg - se->avg.util_avg;
3206 
3207         /* Nothing to update */
3208         if (!delta)
3209                 return;
3210 
3211         /*
3212          * The relation between sum and avg is:
3213          *
3214          *   LOAD_AVG_MAX - 1024 + sa->period_contrib
3215          *
3216          * however, the PELT windows are not aligned between grq and gse.
3217          */
3218 
3219         /* Set new sched_entity's utilization */
3220         se->avg.util_avg = gcfs_rq->avg.util_avg;
3221         se->avg.util_sum = se->avg.util_avg * LOAD_AVG_MAX;
3222 
3223         /* Update parent cfs_rq utilization */
3224         add_positive(&cfs_rq->avg.util_avg, delta);
3225         cfs_rq->avg.util_sum = cfs_rq->avg.util_avg * LOAD_AVG_MAX;
3226 }
3227 
3228 static inline void
3229 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
3230 {
3231         long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
3232         unsigned long runnable_load_avg, load_avg;
3233         u64 runnable_load_sum, load_sum = 0;
3234         s64 delta_sum;
3235 
3236         if (!runnable_sum)
3237                 return;
3238 
3239         gcfs_rq->prop_runnable_sum = 0;
3240 
3241         if (runnable_sum >= 0) {
3242                 /*
3243                  * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
3244                  * the CPU is saturated running == runnable.
3245                  */
3246                 runnable_sum += se->avg.load_sum;
3247                 runnable_sum = min(runnable_sum, (long)LOAD_AVG_MAX);
3248         } else {
3249                 /*
3250                  * Estimate the new unweighted runnable_sum of the gcfs_rq by
3251                  * assuming all tasks are equally runnable.
3252                  */
3253                 if (scale_load_down(gcfs_rq->load.weight)) {
3254                         load_sum = div_s64(gcfs_rq->avg.load_sum,
3255                                 scale_load_down(gcfs_rq->load.weight));
3256                 }
3257 
3258                 /* But make sure to not inflate se's runnable */
3259                 runnable_sum = min(se->avg.load_sum, load_sum);
3260         }
3261 
3262         /*
3263          * runnable_sum can't be lower than running_sum
3264          * As running sum is scale with CPU capacity wehreas the runnable sum
3265          * is not we rescale running_sum 1st
3266          */
3267         running_sum = se->avg.util_sum /
3268                 arch_scale_cpu_capacity(NULL, cpu_of(rq_of(cfs_rq)));
3269         runnable_sum = max(runnable_sum, running_sum);
3270 
3271         load_sum = (s64)se_weight(se) * runnable_sum;
3272         load_avg = div_s64(load_sum, LOAD_AVG_MAX);
3273 
3274         delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
3275         delta_avg = load_avg - se->avg.load_avg;
3276 
3277         se->avg.load_sum = runnable_sum;
3278         se->avg.load_avg = load_avg;
3279         add_positive(&cfs_rq->avg.load_avg, delta_avg);
3280         add_positive(&cfs_rq->avg.load_sum, delta_sum);
3281 
3282         runnable_load_sum = (s64)se_runnable(se) * runnable_sum;
3283         runnable_load_avg = div_s64(runnable_load_sum, LOAD_AVG_MAX);
3284         delta_sum = runnable_load_sum - se_weight(se) * se->avg.runnable_load_sum;
3285         delta_avg = runnable_load_avg - se->avg.runnable_load_avg;
3286 
3287         se->avg.runnable_load_sum = runnable_sum;
3288         se->avg.runnable_load_avg = runnable_load_avg;
3289 
3290         if (se->on_rq) {
3291                 add_positive(&cfs_rq->avg.runnable_load_avg, delta_avg);
3292                 add_positive(&cfs_rq->avg.runnable_load_sum, delta_sum);
3293         }
3294 }
3295 
3296 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
3297 {
3298         cfs_rq->propagate = 1;
3299         cfs_rq->prop_runnable_sum += runnable_sum;
3300 }
3301 
3302 /* Update task and its cfs_rq load average */
3303 static inline int propagate_entity_load_avg(struct sched_entity *se)
3304 {
3305         struct cfs_rq *cfs_rq, *gcfs_rq;
3306 
3307         if (entity_is_task(se))
3308                 return 0;
3309 
3310         gcfs_rq = group_cfs_rq(se);
3311         if (!gcfs_rq->propagate)
3312                 return 0;
3313 
3314         gcfs_rq->propagate = 0;
3315 
3316         cfs_rq = cfs_rq_of(se);
3317 
3318         add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
3319 
3320         update_tg_cfs_util(cfs_rq, se, gcfs_rq);
3321         update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
3322 
3323         return 1;
3324 }
3325 
3326 /*
3327  * Check if we need to update the load and the utilization of a blocked
3328  * group_entity:
3329  */
3330 static inline bool skip_blocked_update(struct sched_entity *se)
3331 {
3332         struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3333 
3334         /*
3335          * If sched_entity still have not zero load or utilization, we have to
3336          * decay it:
3337          */
3338         if (se->avg.load_avg || se->avg.util_avg)
3339                 return false;
3340 
3341         /*
3342          * If there is a pending propagation, we have to update the load and
3343          * the utilization of the sched_entity:
3344          */
3345         if (gcfs_rq->propagate)
3346                 return false;
3347 
3348         /*
3349          * Otherwise, the load and the utilization of the sched_entity is
3350          * already zero and there is no pending propagation, so it will be a
3351          * waste of time to try to decay it:
3352          */
3353         return true;
3354 }
3355 
3356 #else /* CONFIG_FAIR_GROUP_SCHED */
3357 
3358 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq, int force) {}
3359 
3360 static inline int propagate_entity_load_avg(struct sched_entity *se)
3361 {
3362         return 0;
3363 }
3364 
3365 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
3366 
3367 #endif /* CONFIG_FAIR_GROUP_SCHED */
3368 
3369 /**
3370  * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
3371  * @now: current time, as per cfs_rq_clock_task()
3372  * @cfs_rq: cfs_rq to update
3373  *
3374  * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
3375  * avg. The immediate corollary is that all (fair) tasks must be attached, see
3376  * post_init_entity_util_avg().
3377  *
3378  * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
3379  *
3380  * Returns true if the load decayed or we removed load.
3381  *
3382  * Since both these conditions indicate a changed cfs_rq->avg.load we should
3383  * call update_tg_load_avg() when this function returns true.
3384  */
3385 static inline int
3386 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
3387 {
3388         unsigned long removed_load = 0, removed_util = 0, removed_runnable_sum = 0;
3389         struct sched_avg *sa = &cfs_rq->avg;
3390         int decayed = 0;
3391 
3392         if (cfs_rq->removed.nr) {
3393                 unsigned long r;
3394                 u32 divider = LOAD_AVG_MAX - 1024 + sa->period_contrib;
3395 
3396                 raw_spin_lock(&cfs_rq->removed.lock);
3397                 swap(cfs_rq->removed.util_avg, removed_util);
3398                 swap(cfs_rq->removed.load_avg, removed_load);
3399                 swap(cfs_rq->removed.runnable_sum, removed_runnable_sum);
3400                 cfs_rq->removed.nr = 0;
3401                 raw_spin_unlock(&cfs_rq->removed.lock);
3402 
3403                 r = removed_load;
3404                 sub_positive(&sa->load_avg, r);
3405                 sub_positive(&sa->load_sum, r * divider);
3406 
3407                 r = removed_util;
3408                 sub_positive(&sa->util_avg, r);
3409                 sub_positive(&sa->util_sum, r * divider);
3410 
3411                 add_tg_cfs_propagate(cfs_rq, -(long)removed_runnable_sum);
3412 
3413                 decayed = 1;
3414         }
3415 
3416         decayed |= __update_load_avg_cfs_rq(now, cpu_of(rq_of(cfs_rq)), cfs_rq);
3417 
3418 #ifndef CONFIG_64BIT
3419         smp_wmb();
3420         cfs_rq->load_last_update_time_copy = sa->last_update_time;
3421 #endif
3422 
3423         if (decayed)
3424                 cfs_rq_util_change(cfs_rq, 0);
3425 
3426         return decayed;
3427 }
3428 
3429 /**
3430  * attach_entity_load_avg - attach this entity to its cfs_rq load avg
3431  * @cfs_rq: cfs_rq to attach to
3432  * @se: sched_entity to attach
3433  * @flags: migration hints
3434  *
3435  * Must call update_cfs_rq_load_avg() before this, since we rely on
3436  * cfs_rq->avg.last_update_time being current.
3437  */
3438 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3439 {
3440         u32 divider = LOAD_AVG_MAX - 1024 + cfs_rq->avg.period_contrib;
3441 
3442         /*
3443          * When we attach the @se to the @cfs_rq, we must align the decay
3444          * window because without that, really weird and wonderful things can
3445          * happen.
3446          *
3447          * XXX illustrate
3448          */
3449         se->avg.last_update_time = cfs_rq->avg.last_update_time;
3450         se->avg.period_contrib = cfs_rq->avg.period_contrib;
3451 
3452         /*
3453          * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
3454          * period_contrib. This isn't strictly correct, but since we're
3455          * entirely outside of the PELT hierarchy, nobody cares if we truncate
3456          * _sum a little.
3457          */
3458         se->avg.util_sum = se->avg.util_avg * divider;
3459 
3460         se->avg.load_sum = divider;
3461         if (se_weight(se)) {
3462                 se->avg.load_sum =
3463                         div_u64(se->avg.load_avg * se->avg.load_sum, se_weight(se));
3464         }
3465 
3466         se->avg.runnable_load_sum = se->avg.load_sum;
3467 
3468         enqueue_load_avg(cfs_rq, se);
3469         cfs_rq->avg.util_avg += se->avg.util_avg;
3470         cfs_rq->avg.util_sum += se->avg.util_sum;
3471 
3472         add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
3473 
3474         cfs_rq_util_change(cfs_rq, flags);
3475 }
3476 
3477 /**
3478  * detach_entity_load_avg - detach this entity from its cfs_rq load avg
3479  * @cfs_rq: cfs_rq to detach from
3480  * @se: sched_entity to detach
3481  *
3482  * Must call update_cfs_rq_load_avg() before this, since we rely on
3483  * cfs_rq->avg.last_update_time being current.
3484  */
3485 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3486 {
3487         dequeue_load_avg(cfs_rq, se);
3488         sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
3489         sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
3490 
3491         add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
3492 
3493         cfs_rq_util_change(cfs_rq, 0);
3494 }
3495 
3496 /*
3497  * Optional action to be done while updating the load average
3498  */
3499 #define UPDATE_TG       0x1
3500 #define SKIP_AGE_LOAD   0x2
3501 #define DO_ATTACH       0x4
3502 
3503 /* Update task and its cfs_rq load average */
3504 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3505 {
3506         u64 now = cfs_rq_clock_task(cfs_rq);
3507         struct rq *rq = rq_of(cfs_rq);
3508         int cpu = cpu_of(rq);
3509         int decayed;
3510 
3511         /*
3512          * Track task load average for carrying it to new CPU after migrated, and
3513          * track group sched_entity load average for task_h_load calc in migration
3514          */
3515         if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
3516                 __update_load_avg_se(now, cpu, cfs_rq, se);
3517 
3518         decayed  = update_cfs_rq_load_avg(now, cfs_rq);
3519         decayed |= propagate_entity_load_avg(se);
3520 
3521         if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
3522 
3523                 /*
3524                  * DO_ATTACH means we're here from enqueue_entity().
3525                  * !last_update_time means we've passed through
3526                  * migrate_task_rq_fair() indicating we migrated.
3527                  *
3528                  * IOW we're enqueueing a task on a new CPU.
3529                  */
3530                 attach_entity_load_avg(cfs_rq, se, SCHED_CPUFREQ_MIGRATION);
3531                 update_tg_load_avg(cfs_rq, 0);
3532 
3533         } else if (decayed && (flags & UPDATE_TG))
3534                 update_tg_load_avg(cfs_rq, 0);
3535 }
3536 
3537 #ifndef CONFIG_64BIT
3538 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3539 {
3540         u64 last_update_time_copy;
3541         u64 last_update_time;
3542 
3543         do {
3544                 last_update_time_copy = cfs_rq->load_last_update_time_copy;
3545                 smp_rmb();
3546                 last_update_time = cfs_rq->avg.last_update_time;
3547         } while (last_update_time != last_update_time_copy);
3548 
3549         return last_update_time;
3550 }
3551 #else
3552 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3553 {
3554         return cfs_rq->avg.last_update_time;
3555 }
3556 #endif
3557 
3558 /*
3559  * Synchronize entity load avg of dequeued entity without locking
3560  * the previous rq.
3561  */
3562 void sync_entity_load_avg(struct sched_entity *se)
3563 {
3564         struct cfs_rq *cfs_rq = cfs_rq_of(se);
3565         u64 last_update_time;
3566 
3567         last_update_time = cfs_rq_last_update_time(cfs_rq);
3568         __update_load_avg_blocked_se(last_update_time, cpu_of(rq_of(cfs_rq)), se);
3569 }
3570 
3571 /*
3572  * Task first catches up with cfs_rq, and then subtract
3573  * itself from the cfs_rq (task must be off the queue now).
3574  */
3575 void remove_entity_load_avg(struct sched_entity *se)
3576 {
3577         struct cfs_rq *cfs_rq = cfs_rq_of(se);
3578         unsigned long flags;
3579 
3580         /*
3581          * tasks cannot exit without having gone through wake_up_new_task() ->
3582          * post_init_entity_util_avg() which will have added things to the
3583          * cfs_rq, so we can remove unconditionally.
3584          *
3585          * Similarly for groups, they will have passed through
3586          * post_init_entity_util_avg() before unregister_sched_fair_group()
3587          * calls this.
3588          */
3589 
3590         sync_entity_load_avg(se);
3591 
3592         raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
3593         ++cfs_rq->removed.nr;
3594         cfs_rq->removed.util_avg        += se->avg.util_avg;
3595         cfs_rq->removed.load_avg        += se->avg.load_avg;
3596         cfs_rq->removed.runnable_sum    += se->avg.load_sum; /* == runnable_sum */
3597         raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
3598 }
3599 
3600 static inline unsigned long cfs_rq_runnable_load_avg(struct cfs_rq *cfs_rq)
3601 {
3602         return cfs_rq->avg.runnable_load_avg;
3603 }
3604 
3605 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
3606 {
3607         return cfs_rq->avg.load_avg;
3608 }
3609 
3610 static int idle_balance(struct rq *this_rq, struct rq_flags *rf);
3611 
3612 static inline unsigned long task_util(struct task_struct *p)
3613 {
3614         return READ_ONCE(p->se.avg.util_avg);
3615 }
3616 
3617 static inline unsigned long _task_util_est(struct task_struct *p)
3618 {
3619         struct util_est ue = READ_ONCE(p->se.avg.util_est);
3620 
3621         return (max(ue.ewma, ue.enqueued) | UTIL_AVG_UNCHANGED);
3622 }
3623 
3624 static inline unsigned long task_util_est(struct task_struct *p)
3625 {
3626         return max(task_util(p), _task_util_est(p));
3627 }
3628 
3629 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
3630                                     struct task_struct *p)
3631 {
3632         unsigned int enqueued;
3633 
3634         if (!sched_feat(UTIL_EST))
3635                 return;
3636 
3637         /* Update root cfs_rq's estimated utilization */
3638         enqueued  = cfs_rq->avg.util_est.enqueued;
3639         enqueued += _task_util_est(p);
3640         WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
3641 }
3642 
3643 /*
3644  * Check if a (signed) value is within a specified (unsigned) margin,
3645  * based on the observation that:
3646  *
3647  *     abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
3648  *
3649  * NOTE: this only works when value + maring < INT_MAX.
3650  */
3651 static inline bool within_margin(int value, int margin)
3652 {
3653         return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
3654 }
3655 
3656 static void
3657 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p, bool task_sleep)
3658 {
3659         long last_ewma_diff;
3660         struct util_est ue;
3661 
3662         if (!sched_feat(UTIL_EST))
3663                 return;
3664 
3665         /* Update root cfs_rq's estimated utilization */
3666         ue.enqueued  = cfs_rq->avg.util_est.enqueued;
3667         ue.enqueued -= min_t(unsigned int, ue.enqueued, _task_util_est(p));
3668         WRITE_ONCE(cfs_rq->avg.util_est.enqueued, ue.enqueued);
3669 
3670         /*
3671          * Skip update of task's estimated utilization when the task has not
3672          * yet completed an activation, e.g. being migrated.
3673          */
3674         if (!task_sleep)
3675                 return;
3676 
3677         /*
3678          * If the PELT values haven't changed since enqueue time,
3679          * skip the util_est update.
3680          */
3681         ue = p->se.avg.util_est;
3682         if (ue.enqueued & UTIL_AVG_UNCHANGED)
3683                 return;
3684 
3685         /*
3686          * Skip update of task's estimated utilization when its EWMA is
3687          * already ~1% close to its last activation value.
3688          */
3689         ue.enqueued = (task_util(p) | UTIL_AVG_UNCHANGED);
3690         last_ewma_diff = ue.enqueued - ue.ewma;
3691         if (within_margin(last_ewma_diff, (SCHED_CAPACITY_SCALE / 100)))
3692                 return;
3693 
3694         /*
3695          * Update Task's estimated utilization
3696          *
3697          * When *p completes an activation we can consolidate another sample
3698          * of the task size. This is done by storing the current PELT value
3699          * as ue.enqueued and by using this value to update the Exponential
3700          * Weighted Moving Average (EWMA):
3701          *
3702          *  ewma(t) = w *  task_util(p) + (1-w) * ewma(t-1)
3703          *          = w *  task_util(p) +         ewma(t-1)  - w * ewma(t-1)
3704          *          = w * (task_util(p) -         ewma(t-1)) +     ewma(t-1)
3705          *          = w * (      last_ewma_diff            ) +     ewma(t-1)
3706          *          = w * (last_ewma_diff  +  ewma(t-1) / w)
3707          *
3708          * Where 'w' is the weight of new samples, which is configured to be
3709          * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
3710          */
3711         ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
3712         ue.ewma  += last_ewma_diff;
3713         ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
3714         WRITE_ONCE(p->se.avg.util_est, ue);
3715 }
3716 
3717 static inline int task_fits_capacity(struct task_struct *p, long capacity)
3718 {
3719         return capacity * 1024 > task_util_est(p) * capacity_margin;
3720 }
3721 
3722 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
3723 {
3724         if (!static_branch_unlikely(&sched_asym_cpucapacity))
3725                 return;
3726 
3727         if (!p) {
3728                 rq->misfit_task_load = 0;
3729                 return;
3730         }
3731 
3732         if (task_fits_capacity(p, capacity_of(cpu_of(rq)))) {
3733                 rq->misfit_task_load = 0;
3734                 return;
3735         }
3736 
3737         rq->misfit_task_load = task_h_load(p);
3738 }
3739 
3740 #else /* CONFIG_SMP */
3741 
3742 #define UPDATE_TG       0x0
3743 #define SKIP_AGE_LOAD   0x0
3744 #define DO_ATTACH       0x0
3745 
3746 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
3747 {
3748         cfs_rq_util_change(cfs_rq, 0);
3749 }
3750 
3751 static inline void remove_entity_load_avg(struct sched_entity *se) {}
3752 
3753 static inline void
3754 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) {}
3755 static inline void
3756 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
3757 
3758 static inline int idle_balance(struct rq *rq, struct rq_flags *rf)
3759 {
3760         return 0;
3761 }
3762 
3763 static inline void
3764 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
3765 
3766 static inline void
3767 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p,
3768                  bool task_sleep) {}
3769 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
3770 
3771 #endif /* CONFIG_SMP */
3772 
3773 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
3774 {
3775 #ifdef CONFIG_SCHED_DEBUG
3776         s64 d = se->vruntime - cfs_rq->min_vruntime;
3777 
3778         if (d < 0)
3779                 d = -d;
3780 
3781         if (d > 3*sysctl_sched_latency)
3782                 schedstat_inc(cfs_rq->nr_spread_over);
3783 #endif
3784 }
3785 
3786 static void
3787 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
3788 {
3789         u64 vruntime = cfs_rq->min_vruntime;
3790 
3791         /*
3792          * The 'current' period is already promised to the current tasks,
3793          * however the extra weight of the new task will slow them down a
3794          * little, place the new task so that it fits in the slot that
3795          * stays open at the end.
3796          */
3797         if (initial && sched_feat(START_DEBIT))
3798                 vruntime += sched_vslice(cfs_rq, se);
3799 
3800         /* sleeps up to a single latency don't count. */
3801         if (!initial) {
3802                 unsigned long thresh = sysctl_sched_latency;
3803 
3804                 /*
3805                  * Halve their sleep time's effect, to allow
3806                  * for a gentler effect of sleepers:
3807                  */
3808                 if (sched_feat(GENTLE_FAIR_SLEEPERS))
3809                         thresh >>= 1;
3810 
3811                 vruntime -= thresh;
3812         }
3813 
3814         /* ensure we never gain time by being placed backwards. */
3815         se->vruntime = max_vruntime(se->vruntime, vruntime);
3816 }
3817 
3818 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
3819 
3820 static inline void check_schedstat_required(void)
3821 {
3822 #ifdef CONFIG_SCHEDSTATS
3823         if (schedstat_enabled())
3824                 return;
3825 
3826         /* Force schedstat enabled if a dependent tracepoint is active */
3827         if (trace_sched_stat_wait_enabled()    ||
3828                         trace_sched_stat_sleep_enabled()   ||
3829                         trace_sched_stat_iowait_enabled()  ||
3830                         trace_sched_stat_blocked_enabled() ||
3831                         trace_sched_stat_runtime_enabled())  {
3832                 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
3833                              "stat_blocked and stat_runtime require the "
3834                              "kernel parameter schedstats=enable or "
3835                              "kernel.sched_schedstats=1\n");
3836         }
3837 #endif
3838 }
3839 
3840 
3841 /*
3842  * MIGRATION
3843  *
3844  *      dequeue
3845  *        update_curr()
3846  *          update_min_vruntime()
3847  *        vruntime -= min_vruntime
3848  *
3849  *      enqueue
3850  *        update_curr()
3851  *          update_min_vruntime()
3852  *        vruntime += min_vruntime
3853  *
3854  * this way the vruntime transition between RQs is done when both
3855  * min_vruntime are up-to-date.
3856  *
3857  * WAKEUP (remote)
3858  *
3859  *      ->migrate_task_rq_fair() (p->state == TASK_WAKING)
3860  *        vruntime -= min_vruntime
3861  *
3862  *      enqueue
3863  *        update_curr()
3864  *          update_min_vruntime()
3865  *        vruntime += min_vruntime
3866  *
3867  * this way we don't have the most up-to-date min_vruntime on the originating
3868  * CPU and an up-to-date min_vruntime on the destination CPU.
3869  */
3870 
3871 static void
3872 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3873 {
3874         bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
3875         bool curr = cfs_rq->curr == se;
3876 
3877         /*
3878          * If we're the current task, we must renormalise before calling
3879          * update_curr().
3880          */
3881         if (renorm && curr)
3882                 se->vruntime += cfs_rq->min_vruntime;
3883 
3884         update_curr(cfs_rq);
3885 
3886         /*
3887          * Otherwise, renormalise after, such that we're placed at the current
3888          * moment in time, instead of some random moment in the past. Being
3889          * placed in the past could significantly boost this task to the
3890          * fairness detriment of existing tasks.
3891          */
3892         if (renorm && !curr)
3893                 se->vruntime += cfs_rq->min_vruntime;
3894 
3895         /*
3896          * When enqueuing a sched_entity, we must:
3897          *   - Update loads to have both entity and cfs_rq synced with now.
3898          *   - Add its load to cfs_rq->runnable_avg
3899          *   - For group_entity, update its weight to reflect the new share of
3900          *     its group cfs_rq
3901          *   - Add its new weight to cfs_rq->load.weight
3902          */
3903         update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
3904         update_cfs_group(se);
3905         enqueue_runnable_load_avg(cfs_rq, se);
3906         account_entity_enqueue(cfs_rq, se);
3907 
3908         if (flags & ENQUEUE_WAKEUP)
3909                 place_entity(cfs_rq, se, 0);
3910 
3911         check_schedstat_required();
3912         update_stats_enqueue(cfs_rq, se, flags);
3913         check_spread(cfs_rq, se);
3914         if (!curr)
3915                 __enqueue_entity(cfs_rq, se);
3916         se->on_rq = 1;
3917 
3918         if (cfs_rq->nr_running == 1) {
3919                 list_add_leaf_cfs_rq(cfs_rq);
3920                 check_enqueue_throttle(cfs_rq);
3921         }
3922 }
3923 
3924 static void __clear_buddies_last(struct sched_entity *se)
3925 {
3926         for_each_sched_entity(se) {
3927                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3928                 if (cfs_rq->last != se)
3929                         break;
3930 
3931                 cfs_rq->last = NULL;
3932         }
3933 }
3934 
3935 static void __clear_buddies_next(struct sched_entity *se)
3936 {
3937         for_each_sched_entity(se) {
3938                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3939                 if (cfs_rq->next != se)
3940                         break;
3941 
3942                 cfs_rq->next = NULL;
3943         }
3944 }
3945 
3946 static void __clear_buddies_skip(struct sched_entity *se)
3947 {
3948         for_each_sched_entity(se) {
3949                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3950                 if (cfs_rq->skip != se)
3951                         break;
3952 
3953                 cfs_rq->skip = NULL;
3954         }
3955 }
3956 
3957 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
3958 {
3959         if (cfs_rq->last == se)
3960                 __clear_buddies_last(se);
3961 
3962         if (cfs_rq->next == se)
3963                 __clear_buddies_next(se);
3964 
3965         if (cfs_rq->skip == se)
3966                 __clear_buddies_skip(se);
3967 }
3968 
3969 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3970 
3971 static void
3972 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3973 {
3974         /*
3975          * Update run-time statistics of the 'current'.
3976          */
3977         update_curr(cfs_rq);
3978 
3979         /*
3980          * When dequeuing a sched_entity, we must:
3981          *   - Update loads to have both entity and cfs_rq synced with now.
3982          *   - Subtract its load from the cfs_rq->runnable_avg.
3983          *   - Subtract its previous weight from cfs_rq->load.weight.
3984          *   - For group entity, update its weight to reflect the new share
3985          *     of its group cfs_rq.
3986          */
3987         update_load_avg(cfs_rq, se, UPDATE_TG);
3988         dequeue_runnable_load_avg(cfs_rq, se);
3989 
3990         update_stats_dequeue(cfs_rq, se, flags);
3991 
3992         clear_buddies(cfs_rq, se);
3993 
3994         if (se != cfs_rq->curr)
3995                 __dequeue_entity(cfs_rq, se);
3996         se->on_rq = 0;
3997         account_entity_dequeue(cfs_rq, se);
3998 
3999         /*
4000          * Normalize after update_curr(); which will also have moved
4001          * min_vruntime if @se is the one holding it back. But before doing
4002          * update_min_vruntime() again, which will discount @se's position and
4003          * can move min_vruntime forward still more.
4004          */
4005         if (!(flags & DEQUEUE_SLEEP))
4006                 se->vruntime -= cfs_rq->min_vruntime;
4007 
4008         /* return excess runtime on last dequeue */
4009         return_cfs_rq_runtime(cfs_rq);
4010 
4011         update_cfs_group(se);
4012 
4013         /*
4014          * Now advance min_vruntime if @se was the entity holding it back,
4015          * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
4016          * put back on, and if we advance min_vruntime, we'll be placed back
4017          * further than we started -- ie. we'll be penalized.
4018          */
4019         if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
4020                 update_min_vruntime(cfs_rq);
4021 }
4022 
4023 /*
4024  * Preempt the current task with a newly woken task if needed:
4025  */
4026 static void
4027 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4028 {
4029         unsigned long ideal_runtime, delta_exec;
4030         struct sched_entity *se;
4031         s64 delta;
4032 
4033         ideal_runtime = sched_slice(cfs_rq, curr);
4034         delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
4035         if (delta_exec > ideal_runtime) {
4036                 resched_curr(rq_of(cfs_rq));
4037                 /*
4038                  * The current task ran long enough, ensure it doesn't get
4039                  * re-elected due to buddy favours.
4040                  */
4041                 clear_buddies(cfs_rq, curr);
4042                 return;
4043         }
4044 
4045         /*
4046          * Ensure that a task that missed wakeup preemption by a
4047          * narrow margin doesn't have to wait for a full slice.
4048          * This also mitigates buddy induced latencies under load.
4049          */
4050         if (delta_exec < sysctl_sched_min_granularity)
4051                 return;
4052 
4053         se = __pick_first_entity(cfs_rq);
4054         delta = curr->vruntime - se->vruntime;
4055 
4056         if (delta < 0)
4057                 return;
4058 
4059         if (delta > ideal_runtime)
4060                 resched_curr(rq_of(cfs_rq));
4061 }
4062 
4063 static void
4064 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
4065 {
4066         /* 'current' is not kept within the tree. */
4067         if (se->on_rq) {
4068                 /*
4069                  * Any task has to be enqueued before it get to execute on
4070                  * a CPU. So account for the time it spent waiting on the
4071                  * runqueue.
4072                  */
4073                 update_stats_wait_end(cfs_rq, se);
4074                 __dequeue_entity(cfs_rq, se);
4075                 update_load_avg(cfs_rq, se, UPDATE_TG);
4076         }
4077 
4078         update_stats_curr_start(cfs_rq, se);
4079         cfs_rq->curr = se;
4080 
4081         /*
4082          * Track our maximum slice length, if the CPU's load is at
4083          * least twice that of our own weight (i.e. dont track it
4084          * when there are only lesser-weight tasks around):
4085          */
4086         if (schedstat_enabled() && rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
4087                 schedstat_set(se->statistics.slice_max,
4088                         max((u64)schedstat_val(se->statistics.slice_max),
4089                             se->sum_exec_runtime - se->prev_sum_exec_runtime));
4090         }
4091 
4092         se->prev_sum_exec_runtime = se->sum_exec_runtime;
4093 }
4094 
4095 static int
4096 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
4097 
4098 /*
4099  * Pick the next process, keeping these things in mind, in this order:
4100  * 1) keep things fair between processes/task groups
4101  * 2) pick the "next" process, since someone really wants that to run
4102  * 3) pick the "last" process, for cache locality
4103  * 4) do not run the "skip" process, if something else is available
4104  */
4105 static struct sched_entity *
4106 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4107 {
4108         struct sched_entity *left = __pick_first_entity(cfs_rq);
4109         struct sched_entity *se;
4110 
4111         /*
4112          * If curr is set we have to see if its left of the leftmost entity
4113          * still in the tree, provided there was anything in the tree at all.
4114          */
4115         if (!left || (curr && entity_before(curr, left)))
4116                 left = curr;
4117 
4118         se = left; /* ideally we run the leftmost entity */
4119 
4120         /*
4121          * Avoid running the skip buddy, if running something else can
4122          * be done without getting too unfair.
4123          */
4124         if (cfs_rq->skip == se) {
4125                 struct sched_entity *second;
4126 
4127                 if (se == curr) {
4128                         second = __pick_first_entity(cfs_rq);
4129                 } else {
4130                         second = __pick_next_entity(se);
4131                         if (!second || (curr && entity_before(curr, second)))
4132                                 second = curr;
4133                 }
4134 
4135                 if (second && wakeup_preempt_entity(second, left) < 1)
4136                         se = second;
4137         }
4138 
4139         /*
4140          * Prefer last buddy, try to return the CPU to a preempted task.
4141          */
4142         if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
4143                 se = cfs_rq->last;
4144 
4145         /*
4146          * Someone really wants this to run. If it's not unfair, run it.
4147          */
4148         if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
4149                 se = cfs_rq->next;
4150 
4151         clear_buddies(cfs_rq, se);
4152 
4153         return se;
4154 }
4155 
4156 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
4157 
4158 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
4159 {
4160         /*
4161          * If still on the runqueue then deactivate_task()
4162          * was not called and update_curr() has to be done:
4163          */
4164         if (prev->on_rq)
4165                 update_curr(cfs_rq);
4166 
4167         /* throttle cfs_rqs exceeding runtime */
4168         check_cfs_rq_runtime(cfs_rq);
4169 
4170         check_spread(cfs_rq, prev);
4171 
4172         if (prev->on_rq) {
4173                 update_stats_wait_start(cfs_rq, prev);
4174                 /* Put 'current' back into the tree. */
4175                 __enqueue_entity(cfs_rq, prev);
4176                 /* in !on_rq case, update occurred at dequeue */
4177                 update_load_avg(cfs_rq, prev, 0);
4178         }
4179         cfs_rq->curr = NULL;
4180 }
4181 
4182 static void
4183 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
4184 {
4185         /*
4186          * Update run-time statistics of the 'current'.
4187          */
4188         update_curr(cfs_rq);
4189 
4190         /*
4191          * Ensure that runnable average is periodically updated.
4192          */
4193         update_load_avg(cfs_rq, curr, UPDATE_TG);
4194         update_cfs_group(curr);
4195 
4196 #ifdef CONFIG_SCHED_HRTICK
4197         /*
4198          * queued ticks are scheduled to match the slice, so don't bother
4199          * validating it and just reschedule.
4200          */
4201         if (queued) {
4202                 resched_curr(rq_of(cfs_rq));
4203                 return;
4204         }
4205         /*
4206          * don't let the period tick interfere with the hrtick preemption
4207          */
4208         if (!sched_feat(DOUBLE_TICK) &&
4209                         hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
4210                 return;
4211 #endif
4212 
4213         if (cfs_rq->nr_running > 1)
4214                 check_preempt_tick(cfs_rq, curr);
4215 }
4216 
4217 
4218 /**************************************************
4219  * CFS bandwidth control machinery
4220  */
4221 
4222 #ifdef CONFIG_CFS_BANDWIDTH
4223 
4224 #ifdef CONFIG_JUMP_LABEL
4225 static struct static_key __cfs_bandwidth_used;
4226 
4227 static inline bool cfs_bandwidth_used(void)
4228 {
4229         return static_key_false(&__cfs_bandwidth_used);
4230 }
4231 
4232 void cfs_bandwidth_usage_inc(void)
4233 {
4234         static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
4235 }
4236 
4237 void cfs_bandwidth_usage_dec(void)
4238 {
4239         static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
4240 }
4241 #else /* CONFIG_JUMP_LABEL */
4242 static bool cfs_bandwidth_used(void)
4243 {
4244         return true;
4245 }
4246 
4247 void cfs_bandwidth_usage_inc(void) {}
4248 void cfs_bandwidth_usage_dec(void) {}
4249 #endif /* CONFIG_JUMP_LABEL */
4250 
4251 /*
4252  * default period for cfs group bandwidth.
4253  * default: 0.1s, units: nanoseconds
4254  */
4255 static inline u64 default_cfs_period(void)
4256 {
4257         return 100000000ULL;
4258 }
4259 
4260 static inline u64 sched_cfs_bandwidth_slice(void)
4261 {
4262         return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
4263 }
4264 
4265 /*
4266  * Replenish runtime according to assigned quota and update expiration time.
4267  * We use sched_clock_cpu directly instead of rq->clock to avoid adding
4268  * additional synchronization around rq->lock.
4269  *
4270  * requires cfs_b->lock
4271  */
4272 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
4273 {
4274         u64 now;
4275 
4276         if (cfs_b->quota == RUNTIME_INF)
4277                 return;
4278 
4279         now = sched_clock_cpu(smp_processor_id());
4280         cfs_b->runtime = cfs_b->quota;
4281         cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
4282         cfs_b->expires_seq++;
4283 }
4284 
4285 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4286 {
4287         return &tg->cfs_bandwidth;
4288 }
4289 
4290 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
4291 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
4292 {
4293         if (unlikely(cfs_rq->throttle_count))
4294                 return cfs_rq->throttled_clock_task - cfs_rq->throttled_clock_task_time;
4295 
4296         return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
4297 }
4298 
4299 /* returns 0 on failure to allocate runtime */
4300 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4301 {
4302         struct task_group *tg = cfs_rq->tg;
4303         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
4304         u64 amount = 0, min_amount, expires;
4305         int expires_seq;
4306 
4307         /* note: this is a positive sum as runtime_remaining <= 0 */
4308         min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
4309 
4310         raw_spin_lock(&cfs_b->lock);
4311         if (cfs_b->quota == RUNTIME_INF)
4312                 amount = min_amount;
4313         else {
4314                 start_cfs_bandwidth(cfs_b);
4315 
4316                 if (cfs_b->runtime > 0) {
4317                         amount = min(cfs_b->runtime, min_amount);
4318                         cfs_b->runtime -= amount;
4319                         cfs_b->idle = 0;
4320                 }
4321         }
4322         expires_seq = cfs_b->expires_seq;
4323         expires = cfs_b->runtime_expires;
4324         raw_spin_unlock(&cfs_b->lock);
4325 
4326         cfs_rq->runtime_remaining += amount;
4327         /*
4328          * we may have advanced our local expiration to account for allowed
4329          * spread between our sched_clock and the one on which runtime was
4330          * issued.
4331          */
4332         if (cfs_rq->expires_seq != expires_seq) {
4333                 cfs_rq->expires_seq = expires_seq;
4334                 cfs_rq->runtime_expires = expires;
4335         }
4336 
4337         return cfs_rq->runtime_remaining > 0;
4338 }
4339 
4340 /*
4341  * Note: This depends on the synchronization provided by sched_clock and the
4342  * fact that rq->clock snapshots this value.
4343  */
4344 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4345 {
4346         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4347 
4348         /* if the deadline is ahead of our clock, nothing to do */
4349         if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
4350                 return;
4351 
4352         if (cfs_rq->runtime_remaining < 0)
4353                 return;
4354 
4355         /*
4356          * If the local deadline has passed we have to consider the
4357          * possibility that our sched_clock is 'fast' and the global deadline
4358          * has not truly expired.
4359          *
4360          * Fortunately we can check determine whether this the case by checking
4361          * whether the global deadline(cfs_b->expires_seq) has advanced.
4362          */
4363         if (cfs_rq->expires_seq == cfs_b->expires_seq) {
4364                 /* extend local deadline, drift is bounded above by 2 ticks */
4365                 cfs_rq->runtime_expires += TICK_NSEC;
4366         } else {
4367                 /* global deadline is ahead, expiration has passed */
4368                 cfs_rq->runtime_remaining = 0;
4369         }
4370 }
4371 
4372 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4373 {
4374         /* dock delta_exec before expiring quota (as it could span periods) */
4375         cfs_rq->runtime_remaining -= delta_exec;
4376         expire_cfs_rq_runtime(cfs_rq);
4377 
4378         if (likely(cfs_rq->runtime_remaining > 0))
4379                 return;
4380 
4381         /*
4382          * if we're unable to extend our runtime we resched so that the active
4383          * hierarchy can be throttled
4384          */
4385         if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
4386                 resched_curr(rq_of(cfs_rq));
4387 }
4388 
4389 static __always_inline
4390 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4391 {
4392         if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
4393                 return;
4394 
4395         __account_cfs_rq_runtime(cfs_rq, delta_exec);
4396 }
4397 
4398 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4399 {
4400         return cfs_bandwidth_used() && cfs_rq->throttled;
4401 }
4402 
4403 /* check whether cfs_rq, or any parent, is throttled */
4404 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4405 {
4406         return cfs_bandwidth_used() && cfs_rq->throttle_count;
4407 }
4408 
4409 /*
4410  * Ensure that neither of the group entities corresponding to src_cpu or
4411  * dest_cpu are members of a throttled hierarchy when performing group
4412  * load-balance operations.
4413  */
4414 static inline int throttled_lb_pair(struct task_group *tg,
4415                                     int src_cpu, int dest_cpu)
4416 {
4417         struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
4418 
4419         src_cfs_rq = tg->cfs_rq[src_cpu];
4420         dest_cfs_rq = tg->cfs_rq[dest_cpu];
4421 
4422         return throttled_hierarchy(src_cfs_rq) ||
4423                throttled_hierarchy(dest_cfs_rq);
4424 }
4425 
4426 static int tg_unthrottle_up(struct task_group *tg, void *data)
4427 {
4428         struct rq *rq = data;
4429         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4430 
4431         cfs_rq->throttle_count--;
4432         if (!cfs_rq->throttle_count) {
4433                 /* adjust cfs_rq_clock_task() */
4434                 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
4435                                              cfs_rq->throttled_clock_task;
4436         }
4437 
4438         return 0;
4439 }
4440 
4441 static int tg_throttle_down(struct task_group *tg, void *data)
4442 {
4443         struct rq *rq = data;
4444         struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4445 
4446         /* group is entering throttled state, stop time */
4447         if (!cfs_rq->throttle_count)
4448                 cfs_rq->throttled_clock_task = rq_clock_task(rq);
4449         cfs_rq->throttle_count++;
4450 
4451         return 0;
4452 }
4453 
4454 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
4455 {
4456         struct rq *rq = rq_of(cfs_rq);
4457         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4458         struct sched_entity *se;
4459         long task_delta, dequeue = 1;
4460         bool empty;
4461 
4462         se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
4463 
4464         /* freeze hierarchy runnable averages while throttled */
4465         rcu_read_lock();
4466         walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
4467         rcu_read_unlock();
4468 
4469         task_delta = cfs_rq->h_nr_running;
4470         for_each_sched_entity(se) {
4471                 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
4472                 /* throttled entity or throttle-on-deactivate */
4473                 if (!se->on_rq)
4474                         break;
4475 
4476                 if (dequeue)
4477                         dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
4478                 qcfs_rq->h_nr_running -= task_delta;
4479 
4480                 if (qcfs_rq->load.weight)
4481                         dequeue = 0;
4482         }
4483 
4484         if (!se)
4485                 sub_nr_running(rq, task_delta);
4486 
4487         cfs_rq->throttled = 1;
4488         cfs_rq->throttled_clock = rq_clock(rq);
4489         raw_spin_lock(&cfs_b->lock);
4490         empty = list_empty(&cfs_b->throttled_cfs_rq);
4491 
4492         /*
4493          * Add to the _head_ of the list, so that an already-started
4494          * distribute_cfs_runtime will not see us. If disribute_cfs_runtime is
4495          * not running add to the tail so that later runqueues don't get starved.
4496          */
4497         if (cfs_b->distribute_running)
4498                 list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
4499         else
4500                 list_add_tail_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
4501 
4502         /*
4503          * If we're the first throttled task, make sure the bandwidth
4504          * timer is running.
4505          */
4506         if (empty)
4507                 start_cfs_bandwidth(cfs_b);
4508 
4509         raw_spin_unlock(&cfs_b->lock);
4510 }
4511 
4512 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
4513 {
4514         struct rq *rq = rq_of(cfs_rq);
4515         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4516         struct sched_entity *se;
4517         int enqueue = 1;
4518         long task_delta;
4519 
4520         se = cfs_rq->tg->se[cpu_of(rq)];
4521 
4522         cfs_rq->throttled = 0;
4523 
4524         update_rq_clock(rq);
4525 
4526         raw_spin_lock(&cfs_b->lock);
4527         cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
4528         list_del_rcu(&cfs_rq->throttled_list);
4529         raw_spin_unlock(&cfs_b->lock);
4530 
4531         /* update hierarchical throttle state */
4532         walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
4533 
4534         if (!cfs_rq->load.weight)
4535                 return;
4536 
4537         task_delta = cfs_rq->h_nr_running;
4538         for_each_sched_entity(se) {
4539                 if (se->on_rq)
4540                         enqueue = 0;
4541 
4542                 cfs_rq = cfs_rq_of(se);
4543                 if (enqueue)
4544                         enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
4545                 cfs_rq->h_nr_running += task_delta;
4546 
4547                 if (cfs_rq_throttled(cfs_rq))
4548                         break;
4549         }
4550 
4551         if (!se)
4552                 add_nr_running(rq, task_delta);
4553 
4554         /* Determine whether we need to wake up potentially idle CPU: */
4555         if (rq->curr == rq->idle && rq->cfs.nr_running)
4556                 resched_curr(rq);
4557 }
4558 
4559 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
4560                 u64 remaining, u64 expires)
4561 {
4562         struct cfs_rq *cfs_rq;
4563         u64 runtime;
4564         u64 starting_runtime = remaining;
4565 
4566         rcu_read_lock();
4567         list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
4568                                 throttled_list) {
4569                 struct rq *rq = rq_of(cfs_rq);
4570                 struct rq_flags rf;
4571 
4572                 rq_lock(rq, &rf);
4573                 if (!cfs_rq_throttled(cfs_rq))
4574                         goto next;
4575 
4576                 runtime = -cfs_rq->runtime_remaining + 1;
4577                 if (runtime > remaining)
4578                         runtime = remaining;
4579                 remaining -= runtime;
4580 
4581                 cfs_rq->runtime_remaining += runtime;
4582                 cfs_rq->runtime_expires = expires;
4583 
4584                 /* we check whether we're throttled above */
4585                 if (cfs_rq->runtime_remaining > 0)
4586                         unthrottle_cfs_rq(cfs_rq);
4587 
4588 next:
4589                 rq_unlock(rq, &rf);
4590 
4591                 if (!remaining)
4592                         break;
4593         }
4594         rcu_read_unlock();
4595 
4596         return starting_runtime - remaining;
4597 }
4598 
4599 /*
4600  * Responsible for refilling a task_group's bandwidth and unthrottling its
4601  * cfs_rqs as appropriate. If there has been no activity within the last
4602  * period the timer is deactivated until scheduling resumes; cfs_b->idle is
4603  * used to track this state.
4604  */
4605 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
4606 {
4607         u64 runtime, runtime_expires;
4608         int throttled;
4609 
4610         /* no need to continue the timer with no bandwidth constraint */
4611         if (cfs_b->quota == RUNTIME_INF)
4612                 goto out_deactivate;
4613 
4614         throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4615         cfs_b->nr_periods += overrun;
4616 
4617         /*
4618          * idle depends on !throttled (for the case of a large deficit), and if
4619          * we're going inactive then everything else can be deferred
4620          */
4621         if (cfs_b->idle && !throttled)
4622                 goto out_deactivate;
4623 
4624         __refill_cfs_bandwidth_runtime(cfs_b);
4625 
4626         if (!throttled) {
4627                 /* mark as potentially idle for the upcoming period */
4628                 cfs_b->idle = 1;
4629                 return 0;
4630         }
4631 
4632         /* account preceding periods in which throttling occurred */
4633         cfs_b->nr_throttled += overrun;
4634 
4635         runtime_expires = cfs_b->runtime_expires;
4636 
4637         /*
4638          * This check is repeated as we are holding onto the new bandwidth while
4639          * we unthrottle. This can potentially race with an unthrottled group
4640          * trying to acquire new bandwidth from the global pool. This can result
4641          * in us over-using our runtime if it is all used during this loop, but
4642          * only by limited amounts in that extreme case.
4643          */
4644         while (throttled && cfs_b->runtime > 0 && !cfs_b->distribute_running) {
4645                 runtime = cfs_b->runtime;
4646                 cfs_b->distribute_running = 1;
4647                 raw_spin_unlock(&cfs_b->lock);
4648                 /* we can't nest cfs_b->lock while distributing bandwidth */
4649                 runtime = distribute_cfs_runtime(cfs_b, runtime,
4650                                                  runtime_expires);
4651                 raw_spin_lock(&cfs_b->lock);
4652 
4653                 cfs_b->distribute_running = 0;
4654                 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
4655 
4656                 lsub_positive(&cfs_b->runtime, runtime);
4657         }
4658 
4659         /*
4660          * While we are ensured activity in the period following an
4661          * unthrottle, this also covers the case in which the new bandwidth is
4662          * insufficient to cover the existing bandwidth deficit.  (Forcing the
4663          * timer to remain active while there are any throttled entities.)
4664          */
4665         cfs_b->idle = 0;
4666 
4667         return 0;
4668 
4669 out_deactivate:
4670         return 1;
4671 }
4672 
4673 /* a cfs_rq won't donate quota below this amount */
4674 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
4675 /* minimum remaining period time to redistribute slack quota */
4676 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
4677 /* how long we wait to gather additional slack before distributing */
4678 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
4679 
4680 /*
4681  * Are we near the end of the current quota period?
4682  *
4683  * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
4684  * hrtimer base being cleared by hrtimer_start. In the case of
4685  * migrate_hrtimers, base is never cleared, so we are fine.
4686  */
4687 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
4688 {
4689         struct hrtimer *refresh_timer = &cfs_b->period_timer;
4690         u64 remaining;
4691 
4692         /* if the call-back is running a quota refresh is already occurring */
4693         if (hrtimer_callback_running(refresh_timer))
4694                 return 1;
4695 
4696         /* is a quota refresh about to occur? */
4697         remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
4698         if (remaining < min_expire)
4699                 return 1;
4700 
4701         return 0;
4702 }
4703 
4704 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
4705 {
4706         u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
4707 
4708         /* if there's a quota refresh soon don't bother with slack */
4709         if (runtime_refresh_within(cfs_b, min_left))
4710                 return;
4711 
4712         hrtimer_start(&cfs_b->slack_timer,
4713                         ns_to_ktime(cfs_bandwidth_slack_period),
4714                         HRTIMER_MODE_REL);
4715 }
4716 
4717 /* we know any runtime found here is valid as update_curr() precedes return */
4718 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4719 {
4720         struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4721         s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
4722 
4723         if (slack_runtime <= 0)
4724                 return;
4725 
4726         raw_spin_lock(&cfs_b->lock);
4727         if (cfs_b->quota != RUNTIME_INF &&
4728             cfs_rq->runtime_expires == cfs_b->runtime_expires) {
4729                 cfs_b->runtime += slack_runtime;
4730 
4731                 /* we are under rq->lock, defer unthrottling using a timer */
4732                 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
4733                     !list_empty(&cfs_b->throttled_cfs_rq))
4734                         start_cfs_slack_bandwidth(cfs_b);
4735         }
4736         raw_spin_unlock(&cfs_b->lock);
4737 
4738         /* even if it's not valid for return we don't want to try again */
4739         cfs_rq->runtime_remaining -= slack_runtime;
4740 }
4741 
4742 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4743 {
4744         if (!cfs_bandwidth_used())
4745                 return;
4746 
4747         if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
4748                 return;
4749 
4750         __return_cfs_rq_runtime(cfs_rq);
4751 }
4752 
4753 /*
4754  * This is done with a timer (instead of inline with bandwidth return) since
4755  * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
4756  */
4757 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
4758 {
4759         u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
4760         u64 expires;
4761 
4762         /* confirm we're still not at a refresh boundary */
4763         raw_spin_lock(&cfs_b->lock);
4764         if (cfs_b->distribute_running) {
4765                 raw_spin_unlock(&cfs_b->lock);
4766                 return;
4767         }
4768 
4769         if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
4770                 raw_spin_unlock(&cfs_b->lock);
4771                 return;
4772         }
4773 
4774         if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
4775                 runtime = cfs_b->runtime;
4776 
4777         expires = cfs_b->runtime_expires;
4778         if (runtime)
4779                 cfs_b->distribute_running = 1;
4780 
4781         raw_spin_unlock(&cfs_b->lock);
4782 
4783         if (!runtime)
4784                 return;
4785 
4786         runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
4787 
4788         raw_spin_lock(&cfs_b->lock);
4789         if (expires == cfs_b->runtime_expires)
4790                 lsub_positive(&cfs_b->runtime, runtime);
4791         cfs_b->distribute_running = 0;
4792         raw_spin_unlock(&cfs_b->lock);
4793 }
4794 
4795 /*
4796  * When a group wakes up we want to make sure that its quota is not already
4797  * expired/exceeded, otherwise it may be allowed to steal additional ticks of
4798  * runtime as update_curr() throttling can not not trigger until it's on-rq.
4799  */
4800 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
4801 {
4802         if (!cfs_bandwidth_used())
4803                 return;
4804 
4805         /* an active group must be handled by the update_curr()->put() path */
4806         if (!cfs_rq->runtime_enabled || cfs_rq->curr)
4807                 return;
4808 
4809         /* ensure the group is not already throttled */
4810         if (cfs_rq_throttled(cfs_rq))
4811                 return;
4812 
4813         /* update runtime allocation */
4814         account_cfs_rq_runtime(cfs_rq, 0);
4815         if (cfs_rq->runtime_remaining <= 0)
4816                 throttle_cfs_rq(cfs_rq);
4817 }
4818 
4819 static void sync_throttle(struct task_group *tg, int cpu)
4820 {
4821         struct cfs_rq *pcfs_rq, *cfs_rq;
4822 
4823         if (!cfs_bandwidth_used())
4824                 return;
4825 
4826         if (!tg->parent)
4827                 return;
4828 
4829         cfs_rq = tg->cfs_rq[cpu];
4830         pcfs_rq = tg->parent->cfs_rq[cpu];
4831 
4832         cfs_rq->throttle_count = pcfs_rq->throttle_count;
4833         cfs_rq->throttled_clock_task = rq_clock_task(cpu_rq(cpu));
4834 }
4835 
4836 /* conditionally throttle active cfs_rq's from put_prev_entity() */
4837 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4838 {
4839         if (!cfs_bandwidth_used())
4840                 return false;
4841 
4842         if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
4843                 return false;
4844 
4845         /*
4846          * it's possible for a throttled entity to be forced into a running
4847          * state (e.g. set_curr_task), in this case we're finished.
4848          */
4849         if (cfs_rq_throttled(cfs_rq))
4850                 return true;
4851 
4852         throttle_cfs_rq(cfs_rq);
4853         return true;
4854 }
4855 
4856 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
4857 {
4858         struct cfs_bandwidth *cfs_b =
4859                 container_of(timer, struct cfs_bandwidth, slack_timer);
4860 
4861         do_sched_cfs_slack_timer(cfs_b);
4862 
4863         return HRTIMER_NORESTART;
4864 }
4865 
4866 extern const u64 max_cfs_quota_period;
4867 
4868 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
4869 {
4870         struct cfs_bandwidth *cfs_b =
4871                 container_of(timer, struct cfs_bandwidth, period_timer);
4872         int overrun;
4873         int idle = 0;
4874         int count = 0;
4875 
4876         raw_spin_lock(&cfs_b->lock);
4877         for (;;) {
4878                 overrun = hrtimer_forward_now(timer, cfs_b->period);
4879                 if (!overrun)
4880                         break;
4881 
4882                 if (++count > 3) {
4883                         u64 new, old = ktime_to_ns(cfs_b->period);
4884 
4885                         new = (old * 147) / 128; /* ~115% */
4886                         new = min(new, max_cfs_quota_period);
4887 
4888                         cfs_b->period = ns_to_ktime(new);
4889 
4890                         /* since max is 1s, this is limited to 1e9^2, which fits in u64 */
4891                         cfs_b->quota *= new;
4892                         cfs_b->quota = div64_u64(cfs_b->quota, old);
4893 
4894                         pr_warn_ratelimited(
4895         "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us %lld, cfs_quota_us = %lld)\n",
4896                                 smp_processor_id(),
4897                                 div_u64(new, NSEC_PER_USEC),
4898                                 div_u64(cfs_b->quota, NSEC_PER_USEC));
4899 
4900                         /* reset count so we don't come right back in here */
4901                         count = 0;
4902                 }
4903 
4904                 idle = do_sched_cfs_period_timer(cfs_b, overrun);
4905         }
4906         if (idle)
4907                 cfs_b->period_active = 0;
4908         raw_spin_unlock(&cfs_b->lock);
4909 
4910         return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
4911 }
4912 
4913 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4914 {
4915         raw_spin_lock_init(&cfs_b->lock);
4916         cfs_b->runtime = 0;
4917         cfs_b->quota = RUNTIME_INF;
4918         cfs_b->period = ns_to_ktime(default_cfs_period());
4919 
4920         INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
4921         hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
4922         cfs_b->period_timer.function = sched_cfs_period_timer;
4923         hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4924         cfs_b->slack_timer.function = sched_cfs_slack_timer;
4925         cfs_b->distribute_running = 0;
4926 }
4927 
4928 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4929 {
4930         cfs_rq->runtime_enabled = 0;
4931         INIT_LIST_HEAD(&cfs_rq->throttled_list);
4932 }
4933 
4934 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4935 {
4936         u64 overrun;
4937 
4938         lockdep_assert_held(&cfs_b->lock);
4939 
4940         if (cfs_b->period_active)
4941                 return;
4942 
4943         cfs_b->period_active = 1;
4944         overrun = hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
4945         cfs_b->runtime_expires += (overrun + 1) * ktime_to_ns(cfs_b->period);
4946         cfs_b->expires_seq++;
4947         hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
4948 }
4949 
4950 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4951 {
4952         /* init_cfs_bandwidth() was not called */
4953         if (!cfs_b->throttled_cfs_rq.next)
4954                 return;
4955 
4956         hrtimer_cancel(&cfs_b->period_timer);
4957         hrtimer_cancel(&cfs_b->slack_timer);
4958 }
4959 
4960 /*
4961  * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
4962  *
4963  * The race is harmless, since modifying bandwidth settings of unhooked group
4964  * bits doesn't do much.
4965  */
4966 
4967 /* cpu online calback */
4968 static void __maybe_unused update_runtime_enabled(struct rq *rq)
4969 {
4970         struct task_group *tg;
4971 
4972         lockdep_assert_held(&rq->lock);
4973 
4974         rcu_read_lock();
4975         list_for_each_entry_rcu(tg, &task_groups, list) {
4976                 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
4977                 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4978 
4979                 raw_spin_lock(&cfs_b->lock);
4980                 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
4981                 raw_spin_unlock(&cfs_b->lock);
4982         }
4983         rcu_read_unlock();
4984 }
4985 
4986 /* cpu offline callback */
4987 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
4988 {
4989         struct task_group *tg;
4990 
4991         lockdep_assert_held(&rq->lock);
4992 
4993         rcu_read_lock();
4994         list_for_each_entry_rcu(tg, &task_groups, list) {
4995                 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4996 
4997                 if (!cfs_rq->runtime_enabled)
4998                         continue;
4999 
5000                 /*
5001                  * clock_task is not advancing so we just need to make sure
5002                  * there's some valid quota amount
5003                  */
5004                 cfs_rq->runtime_remaining = 1;
5005                 /*
5006                  * Offline rq is schedulable till CPU is completely disabled
5007                  * in take_cpu_down(), so we prevent new cfs throttling here.
5008                  */
5009                 cfs_rq->runtime_enabled = 0;
5010 
5011                 if (cfs_rq_throttled(cfs_rq))
5012                         unthrottle_cfs_rq(cfs_rq);
5013         }
5014         rcu_read_unlock();
5015 }
5016 
5017 #else /* CONFIG_CFS_BANDWIDTH */
5018 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
5019 {
5020         return rq_clock_task(rq_of(cfs_rq));
5021 }
5022 
5023 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
5024 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
5025 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
5026 static inline void sync_throttle(struct task_group *tg, int cpu) {}
5027 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5028 
5029 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5030 {
5031         return 0;
5032 }
5033 
5034 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5035 {
5036         return 0;
5037 }
5038 
5039 static inline int throttled_lb_pair(struct task_group *tg,
5040                                     int src_cpu, int dest_cpu)
5041 {
5042         return 0;
5043 }
5044 
5045 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
5046 
5047 #ifdef CONFIG_FAIR_GROUP_SCHED
5048 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5049 #endif
5050 
5051 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5052 {
5053         return NULL;
5054 }
5055 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
5056 static inline void update_runtime_enabled(struct rq *rq) {}
5057 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
5058 
5059 #endif /* CONFIG_CFS_BANDWIDTH */
5060 
5061 /**************************************************
5062  * CFS operations on tasks:
5063  */
5064 
5065 #ifdef CONFIG_SCHED_HRTICK
5066 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
5067 {
5068         struct sched_entity *se = &p->se;
5069         struct cfs_rq *cfs_rq = cfs_rq_of(se);
5070 
5071         SCHED_WARN_ON(task_rq(p) != rq);
5072 
5073         if (rq->cfs.h_nr_running > 1) {
5074                 u64 slice = sched_slice(cfs_rq, se);
5075                 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
5076                 s64 delta = slice - ran;
5077 
5078                 if (delta < 0) {
5079                         if (rq->curr == p)
5080                                 resched_curr(rq);
5081                         return;
5082                 }
5083                 hrtick_start(rq, delta);
5084         }
5085 }
5086 
5087 /*
5088  * called from enqueue/dequeue and updates the hrtick when the
5089  * current task is from our class and nr_running is low enough
5090  * to matter.
5091  */
5092 static void hrtick_update(struct rq *rq)
5093 {
5094         struct task_struct *curr = rq->curr;
5095 
5096         if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
5097                 return;
5098 
5099         if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
5100                 hrtick_start_fair(rq, curr);
5101 }
5102 #else /* !CONFIG_SCHED_HRTICK */
5103 static inline void
5104 hrtick_start_fair(struct rq *rq, struct task_struct *p)
5105 {
5106 }
5107 
5108 static inline void hrtick_update(struct rq *rq)
5109 {
5110 }
5111 #endif
5112 
5113 #ifdef CONFIG_SMP
5114 static inline unsigned long cpu_util(int cpu);
5115 static unsigned long capacity_of(int cpu);
5116 
5117 static inline bool cpu_overutilized(int cpu)
5118 {
5119         return (capacity_of(cpu) * 1024) < (cpu_util(cpu) * capacity_margin);
5120 }
5121 
5122 static inline void update_overutilized_status(struct rq *rq)
5123 {
5124         if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu))
5125                 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
5126 }
5127 #else
5128 static inline void update_overutilized_status(struct rq *rq) { }
5129 #endif
5130 
5131 /*
5132  * The enqueue_task method is called before nr_running is
5133  * increased. Here we update the fair scheduling stats and
5134  * then put the task into the rbtree:
5135  */
5136 static void
5137 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5138 {
5139         struct cfs_rq *cfs_rq;
5140         struct sched_entity *se = &p->se;
5141 
5142         /*
5143          * The code below (indirectly) updates schedutil which looks at
5144          * the cfs_rq utilization to select a frequency.
5145          * Let's add the task's estimated utilization to the cfs_rq's
5146          * estimated utilization, before we update schedutil.
5147          */
5148         util_est_enqueue(&rq->cfs, p);
5149 
5150         /*
5151          * If in_iowait is set, the code below may not trigger any cpufreq
5152          * utilization updates, so do it here explicitly with the IOWAIT flag
5153          * passed.
5154          */
5155         if (p->in_iowait)
5156                 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
5157 
5158         for_each_sched_entity(se) {
5159                 if (se->on_rq)
5160                         break;
5161                 cfs_rq = cfs_rq_of(se);
5162                 enqueue_entity(cfs_rq, se, flags);
5163 
5164                 /*
5165                  * end evaluation on encountering a throttled cfs_rq
5166                  *
5167                  * note: in the case of encountering a throttled cfs_rq we will
5168                  * post the final h_nr_running increment below.
5169                  */
5170                 if (cfs_rq_throttled(cfs_rq))
5171                         break;
5172                 cfs_rq->h_nr_running++;
5173 
5174                 flags = ENQUEUE_WAKEUP;
5175         }
5176 
5177         for_each_sched_entity(se) {
5178                 cfs_rq = cfs_rq_of(se);
5179                 cfs_rq->h_nr_running++;
5180 
5181                 if (cfs_rq_throttled(cfs_rq))
5182                         break;
5183 
5184                 update_load_avg(cfs_rq, se, UPDATE_TG);
5185                 update_cfs_group(se);
5186         }
5187 
5188         if (!se) {
5189                 add_nr_running(rq, 1);
5190                 /*
5191                  * Since new tasks are assigned an initial util_avg equal to
5192                  * half of the spare capacity of their CPU, tiny tasks have the
5193                  * ability to cross the overutilized threshold, which will
5194                  * result in the load balancer ruining all the task placement
5195                  * done by EAS. As a way to mitigate that effect, do not account
5196                  * for the first enqueue operation of new tasks during the
5197                  * overutilized flag detection.
5198                  *
5199                  * A better way of solving this problem would be to wait for
5200                  * the PELT signals of tasks to converge before taking them
5201                  * into account, but that is not straightforward to implement,
5202                  * and the following generally works well enough in practice.
5203                  */
5204                 if (flags & ENQUEUE_WAKEUP)
5205                         update_overutilized_status(rq);
5206 
5207         }
5208 
5209         hrtick_update(rq);
5210 }
5211 
5212 static void set_next_buddy(struct sched_entity *se);
5213 
5214 /*
5215  * The dequeue_task method is called before nr_running is
5216  * decreased. We remove the task from the rbtree and
5217  * update the fair scheduling stats:
5218  */
5219 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5220 {
5221         struct cfs_rq *cfs_rq;
5222         struct sched_entity *se = &p->se;
5223         int task_sleep = flags & DEQUEUE_SLEEP;
5224 
5225         for_each_sched_entity(se) {
5226                 cfs_rq = cfs_rq_of(se);
5227                 dequeue_entity(cfs_rq, se, flags);
5228 
5229                 /*
5230                  * end evaluation on encountering a throttled cfs_rq
5231                  *
5232                  * note: in the case of encountering a throttled cfs_rq we will
5233                  * post the final h_nr_running decrement below.
5234                 */
5235                 if (cfs_rq_throttled(cfs_rq))
5236                         break;
5237                 cfs_rq->h_nr_running--;
5238 
5239                 /* Don't dequeue parent if it has other entities besides us */
5240                 if (cfs_rq->load.weight) {
5241                         /* Avoid re-evaluating load for this entity: */
5242                         se = parent_entity(se);
5243                         /*
5244                          * Bias pick_next to pick a task from this cfs_rq, as
5245                          * p is sleeping when it is within its sched_slice.
5246                          */
5247                         if (task_sleep && se && !throttled_hierarchy(cfs_rq))
5248                                 set_next_buddy(se);
5249                         break;
5250                 }
5251                 flags |= DEQUEUE_SLEEP;
5252         }
5253 
5254         for_each_sched_entity(se) {
5255                 cfs_rq = cfs_rq_of(se);
5256                 cfs_rq->h_nr_running--;
5257 
5258                 if (cfs_rq_throttled(cfs_rq))
5259                         break;
5260 
5261                 update_load_avg(cfs_rq, se, UPDATE_TG);
5262                 update_cfs_group(se);
5263         }
5264 
5265         if (!se)
5266                 sub_nr_running(rq, 1);
5267 
5268         util_est_dequeue(&rq->cfs, p, task_sleep);
5269         hrtick_update(rq);
5270 }
5271 
5272 #ifdef CONFIG_SMP
5273 
5274 /* Working cpumask for: load_balance, load_balance_newidle. */
5275 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
5276 DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
5277 
5278 #ifdef CONFIG_NO_HZ_COMMON
5279 /*
5280  * per rq 'load' arrray crap; XXX kill this.
5281  */
5282 
5283 /*
5284  * The exact cpuload calculated at every tick would be:
5285  *
5286  *   load' = (1 - 1/2^i) * load + (1/2^i) * cur_load
5287  *
5288  * If a CPU misses updates for n ticks (as it was idle) and update gets
5289  * called on the n+1-th tick when CPU may be busy, then we have:
5290  *
5291  *   load_n   = (1 - 1/2^i)^n * load_0
5292  *   load_n+1 = (1 - 1/2^i)   * load_n + (1/2^i) * cur_load
5293  *
5294  * decay_load_missed() below does efficient calculation of
5295  *
5296  *   load' = (1 - 1/2^i)^n * load
5297  *
5298  * Because x^(n+m) := x^n * x^m we can decompose any x^n in power-of-2 factors.
5299  * This allows us to precompute the above in said factors, thereby allowing the
5300  * reduction of an arbitrary n in O(log_2 n) steps. (See also
5301  * fixed_power_int())
5302  *
5303  * The calculation is approximated on a 128 point scale.
5304  */
5305 #define DEGRADE_SHIFT           7
5306 
5307 static const u8 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
5308 static const u8 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
5309         {   0,   0,  0,  0,  0,  0, 0, 0 },
5310         {  64,  32,  8,  0,  0,  0, 0, 0 },
5311         {  96,  72, 40, 12,  1,  0, 0, 0 },
5312         { 112,  98, 75, 43, 15,  1, 0, 0 },
5313         { 120, 112, 98, 76, 45, 16, 2, 0 }
5314 };
5315 
5316 /*
5317  * Update cpu_load for any missed ticks, due to tickless idle. The backlog
5318  * would be when CPU is idle and so we just decay the old load without
5319  * adding any new load.
5320  */
5321 static unsigned long
5322 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
5323 {
5324         int j = 0;
5325 
5326         if (!missed_updates)
5327                 return load;
5328 
5329         if (missed_updates >= degrade_zero_ticks[idx])
5330                 return 0;
5331 
5332         if (idx == 1)
5333                 return load >> missed_updates;
5334 
5335         while (missed_updates) {
5336                 if (missed_updates % 2)
5337                         load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
5338 
5339                 missed_updates >>= 1;
5340                 j++;
5341         }
5342         return load;
5343 }
5344 
5345 static struct {
5346         cpumask_var_t idle_cpus_mask;
5347         atomic_t nr_cpus;
5348         int has_blocked;                /* Idle CPUS has blocked load */
5349         unsigned long next_balance;     /* in jiffy units */
5350         unsigned long next_blocked;     /* Next update of blocked load in jiffies */
5351 } nohz ____cacheline_aligned;
5352 
5353 #endif /* CONFIG_NO_HZ_COMMON */
5354 
5355 /**
5356  * __cpu_load_update - update the rq->cpu_load[] statistics
5357  * @this_rq: The rq to update statistics for
5358  * @this_load: The current load
5359  * @pending_updates: The number of missed updates
5360  *
5361  * Update rq->cpu_load[] statistics. This function is usually called every
5362  * scheduler tick (TICK_NSEC).
5363  *
5364  * This function computes a decaying average:
5365  *
5366  *   load[i]' = (1 - 1/2^i) * load[i] + (1/2^i) * load
5367  *
5368  * Because of NOHZ it might not get called on every tick which gives need for
5369  * the @pending_updates argument.
5370  *
5371  *   load[i]_n = (1 - 1/2^i) * load[i]_n-1 + (1/2^i) * load_n-1
5372  *             = A * load[i]_n-1 + B ; A := (1 - 1/2^i), B := (1/2^i) * load
5373  *             = A * (A * load[i]_n-2 + B) + B
5374  *             = A * (A * (A * load[i]_n-3 + B) + B) + B
5375  *             = A^3 * load[i]_n-3 + (A^2 + A + 1) * B
5376  *             = A^n * load[i]_0 + (A^(n-1) + A^(n-2) + ... + 1) * B
5377  *             = A^n * load[i]_0 + ((1 - A^n) / (1 - A)) * B
5378  *             = (1 - 1/2^i)^n * (load[i]_0 - load) + load
5379  *
5380  * In the above we've assumed load_n := load, which is true for NOHZ_FULL as
5381  * any change in load would have resulted in the tick being turned back on.
5382  *
5383  * For regular NOHZ, this reduces to:
5384  *
5385  *   load[i]_n = (1 - 1/2^i)^n * load[i]_0
5386  *
5387  * see decay_load_misses(). For NOHZ_FULL we get to subtract and add the extra
5388  * term.
5389  */
5390 static void cpu_load_update(struct rq *this_rq, unsigned long this_load,
5391                             unsigned long pending_updates)
5392 {
5393         unsigned long __maybe_unused tickless_load = this_rq->cpu_load[0];
5394         int i, scale;
5395 
5396         this_rq->nr_load_updates++;
5397 
5398         /* Update our load: */
5399         this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
5400         for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
5401                 unsigned long old_load, new_load;
5402 
5403                 /* scale is effectively 1 << i now, and >> i divides by scale */
5404 
5405                 old_load = this_rq->cpu_load[i];
5406 #ifdef CONFIG_NO_HZ_COMMON
5407                 old_load = decay_load_missed(old_load, pending_updates - 1, i);
5408                 if (tickless_load) {
5409                         old_load -= decay_load_missed(tickless_load, pending_updates - 1, i);
5410                         /*
5411                          * old_load can never be a negative value because a
5412                          * decayed tickless_load cannot be greater than the
5413                          * original tickless_load.
5414                          */
5415                         old_load += tickless_load;
5416                 }
5417 #endif
5418                 new_load = this_load;
5419                 /*
5420                  * Round up the averaging division if load is increasing. This
5421                  * prevents us from getting stuck on 9 if the load is 10, for
5422                  * example.
5423                  */
5424                 if (new_load > old_load)
5425                         new_load += scale - 1;
5426 
5427                 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
5428         }
5429 }
5430 
5431 /* Used instead of source_load when we know the type == 0 */
5432 static unsigned long weighted_cpuload(struct rq *rq)
5433 {
5434         return cfs_rq_runnable_load_avg(&rq->cfs);
5435 }
5436 
5437 #ifdef CONFIG_NO_HZ_COMMON
5438 /*
5439  * There is no sane way to deal with nohz on smp when using jiffies because the
5440  * CPU doing the jiffies update might drift wrt the CPU doing the jiffy reading
5441  * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}.
5442  *
5443  * Therefore we need to avoid the delta approach from the regular tick when
5444  * possible since that would seriously skew the load calculation. This is why we
5445  * use cpu_load_update_periodic() for CPUs out of nohz. However we'll rely on
5446  * jiffies deltas for updates happening while in nohz mode (idle ticks, idle
5447  * loop exit, nohz_idle_balance, nohz full exit...)
5448  *
5449  * This means we might still be one tick off for nohz periods.
5450  */
5451 
5452 static void cpu_load_update_nohz(struct rq *this_rq,
5453                                  unsigned long curr_jiffies,
5454                                  unsigned long load)
5455 {
5456         unsigned long pending_updates;
5457 
5458         pending_updates = curr_jiffies - this_rq->last_load_update_tick;
5459         if (pending_updates) {
5460                 this_rq->last_load_update_tick = curr_jiffies;
5461                 /*
5462                  * In the regular NOHZ case, we were idle, this means load 0.
5463                  * In the NOHZ_FULL case, we were non-idle, we should consider
5464                  * its weighted load.
5465                  */
5466                 cpu_load_update(this_rq, load, pending_updates);
5467         }
5468 }
5469 
5470 /*
5471  * Called from nohz_idle_balance() to update the load ratings before doing the
5472  * idle balance.
5473  */
5474 static void cpu_load_update_idle(struct rq *this_rq)
5475 {
5476         /*
5477          * bail if there's load or we're actually up-to-date.
5478          */
5479         if (weighted_cpuload(this_rq))
5480                 return;
5481 
5482         cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), 0);
5483 }
5484 
5485 /*
5486  * Record CPU load on nohz entry so we know the tickless load to account
5487  * on nohz exit. cpu_load[0] happens then to be updated more frequently
5488  * than other cpu_load[idx] but it should be fine as cpu_load readers
5489  * shouldn't rely into synchronized cpu_load[*] updates.
5490  */
5491 void cpu_load_update_nohz_start(void)
5492 {
5493         struct rq *this_rq = this_rq();
5494 
5495         /*
5496          * This is all lockless but should be fine. If weighted_cpuload changes
5497          * concurrently we'll exit nohz. And cpu_load write can race with
5498          * cpu_load_update_idle() but both updater would be writing the same.
5499          */
5500         this_rq->cpu_load[0] = weighted_cpuload(this_rq);
5501 }
5502 
5503 /*
5504  * Account the tickless load in the end of a nohz frame.
5505  */
5506 void cpu_load_update_nohz_stop(void)
5507 {
5508         unsigned long curr_jiffies = READ_ONCE(jiffies);
5509         struct rq *this_rq = this_rq();
5510         unsigned long load;
5511         struct rq_flags rf;
5512 
5513         if (curr_jiffies == this_rq->last_load_update_tick)
5514                 return;
5515 
5516         load = weighted_cpuload(this_rq);
5517         rq_lock(this_rq, &rf);
5518         update_rq_clock(this_rq);
5519         cpu_load_update_nohz(this_rq, curr_jiffies, load);
5520         rq_unlock(this_rq, &rf);
5521 }
5522 #else /* !CONFIG_NO_HZ_COMMON */
5523 static inline void cpu_load_update_nohz(struct rq *this_rq,
5524                                         unsigned long curr_jiffies,
5525                                         unsigned long load) { }
5526 #endif /* CONFIG_NO_HZ_COMMON */
5527 
5528 static void cpu_load_update_periodic(struct rq *this_rq, unsigned long load)
5529 {
5530 #ifdef CONFIG_NO_HZ_COMMON
5531         /* See the mess around cpu_load_update_nohz(). */
5532         this_rq->last_load_update_tick = READ_ONCE(jiffies);
5533 #endif
5534         cpu_load_update(this_rq, load, 1);
5535 }
5536 
5537 /*
5538  * Called from scheduler_tick()
5539  */
5540 void cpu_load_update_active(struct rq *this_rq)
5541 {
5542         unsigned long load = weighted_cpuload(this_rq);
5543 
5544         if (tick_nohz_tick_stopped())
5545                 cpu_load_update_nohz(this_rq, READ_ONCE(jiffies), load);
5546         else
5547                 cpu_load_update_periodic(this_rq, load);
5548 }
5549 
5550 /*
5551  * Return a low guess at the load of a migration-source CPU weighted
5552  * according to the scheduling class and "nice" value.
5553  *
5554  * We want to under-estimate the load of migration sources, to
5555  * balance conservatively.
5556  */
5557 static unsigned long source_load(int cpu, int type)
5558 {
5559         struct rq *rq = cpu_rq(cpu);
5560         unsigned long total = weighted_cpuload(rq);
5561 
5562         if (type == 0 || !sched_feat(LB_BIAS))
5563                 return total;
5564 
5565         return min(rq->cpu_load[type-1], total);
5566 }
5567 
5568 /*
5569  * Return a high guess at the load of a migration-target CPU weighted
5570  * according to the scheduling class and "nice" value.
5571  */
5572 static unsigned long target_load(int cpu, int type)
5573 {
5574         struct rq *rq = cpu_rq(cpu);
5575         unsigned long total = weighted_cpuload(rq);
5576 
5577         if (type == 0 || !sched_feat(LB_BIAS))
5578                 return total;
5579 
5580         return max(rq->cpu_load[type-1], total);
5581 }
5582 
5583 static unsigned long capacity_of(int cpu)
5584 {
5585         return cpu_rq(cpu)->cpu_capacity;
5586 }
5587 
5588 static unsigned long capacity_orig_of(int cpu)
5589 {
5590         return cpu_rq(cpu)->cpu_capacity_orig;
5591 }
5592 
5593 static unsigned long cpu_avg_load_per_task(int cpu)
5594 {
5595         struct rq *rq = cpu_rq(cpu);
5596         unsigned long nr_running = READ_ONCE(rq->cfs.h_nr_running);
5597         unsigned long load_avg = weighted_cpuload(rq);
5598 
5599         if (nr_running)
5600                 return load_avg / nr_running;
5601 
5602         return 0;
5603 }
5604 
5605 static void record_wakee(struct task_struct *p)
5606 {
5607         /*
5608          * Only decay a single time; tasks that have less then 1 wakeup per
5609          * jiffy will not have built up many flips.
5610          */
5611         if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
5612                 current->wakee_flips >>= 1;
5613                 current->wakee_flip_decay_ts = jiffies;
5614         }
5615 
5616         if (current->last_wakee != p) {
5617                 current->last_wakee = p;
5618                 current->wakee_flips++;
5619         }
5620 }
5621 
5622 /*
5623  * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
5624  *
5625  * A waker of many should wake a different task than the one last awakened
5626  * at a frequency roughly N times higher than one of its wakees.
5627  *
5628  * In order to determine whether we should let the load spread vs consolidating
5629  * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
5630  * partner, and a factor of lls_size higher frequency in the other.
5631  *
5632  * With both conditions met, we can be relatively sure that the relationship is
5633  * non-monogamous, with partner count exceeding socket size.
5634  *
5635  * Waker/wakee being client/server, worker/dispatcher, interrupt source or
5636  * whatever is irrelevant, spread criteria is apparent partner count exceeds
5637  * socket size.
5638  */
5639 static int wake_wide(struct task_struct *p)
5640 {
5641         unsigned int master = current->wakee_flips;
5642         unsigned int slave = p->wakee_flips;
5643         int factor = this_cpu_read(sd_llc_size);
5644 
5645         if (master < slave)
5646                 swap(master, slave);
5647         if (slave < factor || master < slave * factor)
5648                 return 0;
5649         return 1;
5650 }
5651 
5652 /*
5653  * The purpose of wake_affine() is to quickly determine on which CPU we can run
5654  * soonest. For the purpose of speed we only consider the waking and previous
5655  * CPU.
5656  *
5657  * wake_affine_idle() - only considers 'now', it check if the waking CPU is
5658  *                      cache-affine and is (or will be) idle.
5659  *
5660  * wake_affine_weight() - considers the weight to reflect the average
5661  *                        scheduling latency of the CPUs. This seems to work
5662  *                        for the overloaded case.
5663  */
5664 static int
5665 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
5666 {
5667         /*
5668          * If this_cpu is idle, it implies the wakeup is from interrupt
5669          * context. Only allow the move if cache is shared. Otherwise an
5670          * interrupt intensive workload could force all tasks onto one
5671          * node depending on the IO topology or IRQ affinity settings.
5672          *
5673          * If the prev_cpu is idle and cache affine then avoid a migration.
5674          * There is no guarantee that the cache hot data from an interrupt
5675          * is more important than cache hot data on the prev_cpu and from
5676          * a cpufreq perspective, it's better to have higher utilisation
5677          * on one CPU.
5678          */
5679         if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
5680                 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
5681 
5682         if (sync && cpu_rq(this_cpu)->nr_running == 1)
5683                 return this_cpu;
5684 
5685         return nr_cpumask_bits;
5686 }
5687 
5688 static int
5689 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
5690                    int this_cpu, int prev_cpu, int sync)
5691 {
5692         s64 this_eff_load, prev_eff_load;
5693         unsigned long task_load;
5694 
5695         this_eff_load = target_load(this_cpu, sd->wake_idx);
5696 
5697         if (sync) {
5698                 unsigned long current_load = task_h_load(current);
5699 
5700                 if (current_load > this_eff_load)
5701                         return this_cpu;
5702 
5703                 this_eff_load -= current_load;
5704         }
5705 
5706         task_load = task_h_load(p);
5707 
5708         this_eff_load += task_load;
5709         if (sched_feat(WA_BIAS))
5710                 this_eff_load *= 100;
5711         this_eff_load *= capacity_of(prev_cpu);
5712 
5713         prev_eff_load = source_load(prev_cpu, sd->wake_idx);
5714         prev_eff_load -= task_load;
5715         if (sched_feat(WA_BIAS))
5716                 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
5717         prev_eff_load *= capacity_of(this_cpu);
5718 
5719         /*
5720          * If sync, adjust the weight of prev_eff_load such that if
5721          * prev_eff == this_eff that select_idle_sibling() will consider
5722          * stacking the wakee on top of the waker if no other CPU is
5723          * idle.
5724          */
5725         if (sync)
5726                 prev_eff_load += 1;
5727 
5728         return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
5729 }
5730 
5731 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
5732                        int this_cpu, int prev_cpu, int sync)
5733 {
5734         int target = nr_cpumask_bits;
5735 
5736         if (sched_feat(WA_IDLE))
5737                 target = wake_affine_idle(this_cpu, prev_cpu, sync);
5738 
5739         if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
5740                 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
5741 
5742         schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
5743         if (target == nr_cpumask_bits)
5744                 return prev_cpu;
5745 
5746         schedstat_inc(sd->ttwu_move_affine);
5747         schedstat_inc(p->se.statistics.nr_wakeups_affine);
5748         return target;
5749 }
5750 
5751 static unsigned long cpu_util_without(int cpu, struct task_struct *p);
5752 
5753 static unsigned long capacity_spare_without(int cpu, struct task_struct *p)
5754 {
5755         return max_t(long, capacity_of(cpu) - cpu_util_without(cpu, p), 0);
5756 }
5757 
5758 /*
5759  * find_idlest_group finds and returns the least busy CPU group within the
5760  * domain.
5761  *
5762  * Assumes p is allowed on at least one CPU in sd.
5763  */
5764 static struct sched_group *
5765 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
5766                   int this_cpu, int sd_flag)
5767 {
5768         struct sched_group *idlest = NULL, *group = sd->groups;
5769         struct sched_group *most_spare_sg = NULL;
5770         unsigned long min_runnable_load = ULONG_MAX;
5771         unsigned long this_runnable_load = ULONG_MAX;
5772         unsigned long min_avg_load = ULONG_MAX, this_avg_load = ULONG_MAX;
5773         unsigned long most_spare = 0, this_spare = 0;
5774         int load_idx = sd->forkexec_idx;
5775         int imbalance_scale = 100 + (sd->imbalance_pct-100)/2;
5776         unsigned long imbalance = scale_load_down(NICE_0_LOAD) *
5777                                 (sd->imbalance_pct-100) / 100;
5778 
5779         if (sd_flag & SD_BALANCE_WAKE)
5780                 load_idx = sd->wake_idx;
5781 
5782         do {
5783                 unsigned long load, avg_load, runnable_load;
5784                 unsigned long spare_cap, max_spare_cap;
5785                 int local_group;
5786                 int i;
5787 
5788                 /* Skip over this group if it has no CPUs allowed */
5789                 if (!cpumask_intersects(sched_group_span(group),
5790                                         &p->cpus_allowed))
5791                         continue;
5792 
5793                 local_group = cpumask_test_cpu(this_cpu,
5794                                                sched_group_span(group));
5795 
5796                 /*
5797                  * Tally up the load of all CPUs in the group and find
5798                  * the group containing the CPU with most spare capacity.
5799                  */
5800                 avg_load = 0;
5801                 runnable_load = 0;
5802                 max_spare_cap = 0;
5803 
5804                 for_each_cpu(i, sched_group_span(group)) {
5805                         /* Bias balancing toward CPUs of our domain */
5806                         if (local_group)
5807                                 load = source_load(i, load_idx);
5808                         else
5809                                 load = target_load(i, load_idx);
5810 
5811                         runnable_load += load;
5812 
5813                         avg_load += cfs_rq_load_avg(&cpu_rq(i)->cfs);
5814 
5815                         spare_cap = capacity_spare_without(i, p);
5816 
5817                         if (spare_cap > max_spare_cap)
5818                                 max_spare_cap = spare_cap;
5819                 }
5820 
5821                 /* Adjust by relative CPU capacity of the group */
5822                 avg_load = (avg_load * SCHED_CAPACITY_SCALE) /
5823                                         group->sgc->capacity;
5824                 runnable_load = (runnable_load * SCHED_CAPACITY_SCALE) /
5825                                         group->sgc->capacity;
5826 
5827                 if (local_group) {
5828                         this_runnable_load = runnable_load;
5829                         this_avg_load = avg_load;
5830                         this_spare = max_spare_cap;
5831                 } else {
5832                         if (min_runnable_load > (runnable_load + imbalance)) {
5833                                 /*
5834                                  * The runnable load is significantly smaller
5835                                  * so we can pick this new CPU:
5836                                  */
5837                                 min_runnable_load = runnable_load;
5838                                 min_avg_load = avg_load;
5839                                 idlest = group;
5840                         } else if ((runnable_load < (min_runnable_load + imbalance)) &&
5841                                    (100*min_avg_load > imbalance_scale*avg_load)) {
5842                                 /*
5843                                  * The runnable loads are close so take the
5844                                  * blocked load into account through avg_load:
5845                                  */
5846                                 min_avg_load = avg_load;
5847                                 idlest = group;
5848                         }
5849 
5850                         if (most_spare < max_spare_cap) {
5851                                 most_spare = max_spare_cap;
5852                                 most_spare_sg = group;
5853                         }
5854                 }
5855         } while (group = group->next, group != sd->groups);
5856 
5857         /*
5858          * The cross-over point between using spare capacity or least load
5859          * is too conservative for high utilization tasks on partially
5860          * utilized systems if we require spare_capacity > task_util(p),
5861          * so we allow for some task stuffing by using
5862          * spare_capacity > task_util(p)/2.
5863          *
5864          * Spare capacity can't be used for fork because the utilization has
5865          * not been set yet, we must first select a rq to compute the initial
5866          * utilization.
5867          */
5868         if (sd_flag & SD_BALANCE_FORK)
5869                 goto skip_spare;
5870 
5871         if (this_spare > task_util(p) / 2 &&
5872             imbalance_scale*this_spare > 100*most_spare)
5873                 return NULL;
5874 
5875         if (most_spare > task_util(p) / 2)
5876                 return most_spare_sg;
5877 
5878 skip_spare:
5879         if (!idlest)
5880                 return NULL;
5881 
5882         /*
5883          * When comparing groups across NUMA domains, it's possible for the
5884          * local domain to be very lightly loaded relative to the remote
5885          * domains but "imbalance" skews the comparison making remote CPUs
5886          * look much more favourable. When considering cross-domain, add
5887          * imbalance to the runnable load on the remote node and consider
5888          * staying local.
5889          */
5890         if ((sd->flags & SD_NUMA) &&
5891             min_runnable_load + imbalance >= this_runnable_load)
5892                 return NULL;
5893 
5894         if (min_runnable_load > (this_runnable_load + imbalance))
5895                 return NULL;
5896 
5897         if ((this_runnable_load < (min_runnable_load + imbalance)) &&
5898              (100*this_avg_load < imbalance_scale*min_avg_load))
5899                 return NULL;
5900 
5901         return idlest;
5902 }
5903 
5904 /*
5905  * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
5906  */
5907 static int
5908 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
5909 {
5910         unsigned long load, min_load = ULONG_MAX;
5911         unsigned int min_exit_latency = UINT_MAX;
5912         u64 latest_idle_timestamp = 0;
5913         int least_loaded_cpu = this_cpu;
5914         int shallowest_idle_cpu = -1;
5915         int i;
5916 
5917         /* Check if we have any choice: */
5918         if (group->group_weight == 1)
5919                 return cpumask_first(sched_group_span(group));
5920 
5921         /* Traverse only the allowed CPUs */
5922         for_each_cpu_and(i, sched_group_span(group), &p->cpus_allowed) {
5923                 if (available_idle_cpu(i)) {
5924                         struct rq *rq = cpu_rq(i);
5925                         struct cpuidle_state *idle = idle_get_state(rq);
5926                         if (idle && idle->exit_latency < min_exit_latency) {
5927                                 /*
5928                                  * We give priority to a CPU whose idle state
5929                                  * has the smallest exit latency irrespective
5930                                  * of any idle timestamp.
5931                                  */
5932                                 min_exit_latency = idle->exit_latency;
5933                                 latest_idle_timestamp = rq->idle_stamp;
5934                                 shallowest_idle_cpu = i;
5935                         } else if ((!idle || idle->exit_latency == min_exit_latency) &&
5936                                    rq->idle_stamp > latest_idle_timestamp) {
5937                                 /*
5938                                  * If equal or no active idle state, then
5939                                  * the most recently idled CPU might have
5940                                  * a warmer cache.
5941                                  */
5942                                 latest_idle_timestamp = rq->idle_stamp;
5943                                 shallowest_idle_cpu = i;
5944                         }
5945                 } else if (shallowest_idle_cpu == -1) {
5946                         load = weighted_cpuload(cpu_rq(i));
5947                         if (load < min_load) {
5948                                 min_load = load;
5949                                 least_loaded_cpu = i;
5950                         }
5951                 }
5952         }
5953 
5954         return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
5955 }
5956 
5957 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
5958                                   int cpu, int prev_cpu, int sd_flag)
5959 {
5960         int new_cpu = cpu;
5961 
5962         if (!cpumask_intersects(sched_domain_span(sd), &p->cpus_allowed))
5963                 return prev_cpu;
5964 
5965         /*
5966          * We need task's util for capacity_spare_without, sync it up to
5967          * prev_cpu's last_update_time.
5968          */
5969         if (!(sd_flag & SD_BALANCE_FORK))
5970                 sync_entity_load_avg(&p->se);
5971 
5972         while (sd) {
5973                 struct sched_group *group;
5974                 struct sched_domain *tmp;
5975                 int weight;
5976 
5977                 if (!(sd->flags & sd_flag)) {
5978                         sd = sd->child;
5979                         continue;
5980                 }
5981 
5982                 group = find_idlest_group(sd, p, cpu, sd_flag);
5983                 if (!group) {
5984                         sd = sd->child;
5985                         continue;
5986                 }
5987 
5988                 new_cpu = find_idlest_group_cpu(group, p, cpu);
5989                 if (new_cpu == cpu) {
5990                         /* Now try balancing at a lower domain level of 'cpu': */
5991                         sd = sd->child;
5992                         continue;
5993                 }
5994 
5995                 /* Now try balancing at a lower domain level of 'new_cpu': */
5996                 cpu = new_cpu;
5997                 weight = sd->span_weight;
5998                 sd = NULL;
5999                 for_each_domain(cpu, tmp) {
6000                         if (weight <= tmp->span_weight)
6001                                 break;
6002                         if (tmp->flags & sd_flag)
6003                                 sd = tmp;
6004                 }
6005         }
6006 
6007         return new_cpu;
6008 }
6009 
6010 #ifdef CONFIG_SCHED_SMT
6011 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
6012 EXPORT_SYMBOL_GPL(sched_smt_present);
6013 
6014 static inline void set_idle_cores(int cpu, int val)
6015 {
6016         struct sched_domain_shared *sds;
6017 
6018         sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6019         if (sds)
6020                 WRITE_ONCE(sds->has_idle_cores, val);
6021 }
6022 
6023 static inline bool test_idle_cores(int cpu, bool def)
6024 {
6025         struct sched_domain_shared *sds;
6026 
6027         sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6028         if (sds)
6029                 return READ_ONCE(sds->has_idle_cores);
6030 
6031         return def;
6032 }
6033 
6034 /*
6035  * Scans the local SMT mask to see if the entire core is idle, and records this
6036  * information in sd_llc_shared->has_idle_cores.
6037  *
6038  * Since SMT siblings share all cache levels, inspecting this limited remote
6039  * state should be fairly cheap.
6040  */
6041 void __update_idle_core(struct rq *rq)
6042 {
6043         int core = cpu_of(rq);
6044         int cpu;
6045 
6046         rcu_read_lock();
6047         if (test_idle_cores(core, true))
6048                 goto unlock;
6049 
6050         for_each_cpu(cpu, cpu_smt_mask(core)) {
6051                 if (cpu == core)
6052                         continue;
6053 
6054                 if (!available_idle_cpu(cpu))
6055                         goto unlock;
6056         }
6057 
6058         set_idle_cores(core, 1);
6059 unlock:
6060         rcu_read_unlock();
6061 }
6062 
6063 /*
6064  * Scan the entire LLC domain for idle cores; this dynamically switches off if
6065  * there are no idle cores left in the system; tracked through
6066  * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
6067  */
6068 static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
6069 {
6070         struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6071         int core, cpu;
6072 
6073         if (!static_branch_likely(&sched_smt_present))
6074                 return -1;
6075 
6076         if (!test_idle_cores(target, false))
6077                 return -1;
6078 
6079         cpumask_and(cpus, sched_domain_span(sd), &p->cpus_allowed);
6080 
6081         for_each_cpu_wrap(core, cpus, target) {
6082                 bool idle = true;
6083 
6084                 for_each_cpu(cpu, cpu_smt_mask(core)) {
6085                         cpumask_clear_cpu(cpu, cpus);
6086                         if (!available_idle_cpu(cpu))
6087                                 idle = false;
6088                 }
6089 
6090                 if (idle)
6091                         return core;
6092         }
6093 
6094         /*
6095          * Failed to find an idle core; stop looking for one.
6096          */
6097         set_idle_cores(target, 0);
6098 
6099         return -1;
6100 }
6101 
6102 /*
6103  * Scan the local SMT mask for idle CPUs.
6104  */
6105 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6106 {
6107         int cpu;
6108 
6109         if (!static_branch_likely(&sched_smt_present))
6110                 return -1;
6111 
6112         for_each_cpu(cpu, cpu_smt_mask(target)) {
6113                 if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
6114                         continue;
6115                 if (available_idle_cpu(cpu))
6116                         return cpu;
6117         }
6118 
6119         return -1;
6120 }
6121 
6122 #else /* CONFIG_SCHED_SMT */
6123 
6124 static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
6125 {
6126         return -1;
6127 }
6128 
6129 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6130 {
6131         return -1;
6132 }
6133 
6134 #endif /* CONFIG_SCHED_SMT */
6135 
6136 /*
6137  * Scan the LLC domain for idle CPUs; this is dynamically regulated by
6138  * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
6139  * average idle time for this rq (as found in rq->avg_idle).
6140  */
6141 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
6142 {
6143         struct sched_domain *this_sd;
6144         u64 avg_cost, avg_idle;
6145         u64 time, cost;
6146         s64 delta;
6147         int cpu, nr = INT_MAX;
6148 
6149         this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
6150         if (!this_sd)
6151                 return -1;
6152 
6153         /*
6154          * Due to large variance we need a large fuzz factor; hackbench in
6155          * particularly is sensitive here.
6156          */
6157         avg_idle = this_rq()->avg_idle / 512;
6158         avg_cost = this_sd->avg_scan_cost + 1;
6159 
6160         if (sched_feat(SIS_AVG_CPU) && avg_idle < avg_cost)
6161                 return -1;
6162 
6163         if (sched_feat(SIS_PROP)) {
6164                 u64 span_avg = sd->span_weight * avg_idle;
6165                 if (span_avg > 4*avg_cost)
6166                         nr = div_u64(span_avg, avg_cost);
6167                 else
6168                         nr = 4;
6169         }
6170 
6171         time = local_clock();
6172 
6173         for_each_cpu_wrap(cpu, sched_domain_span(sd), target) {
6174                 if (!--nr)
6175                         return -1;
6176                 if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
6177                         continue;
6178                 if (available_idle_cpu(cpu))
6179                         break;
6180         }
6181 
6182         time = local_clock() - time;
6183         cost = this_sd->avg_scan_cost;
6184         delta = (s64)(time - cost) / 8;
6185         this_sd->avg_scan_cost += delta;
6186 
6187         return cpu;
6188 }
6189 
6190 /*
6191  * Try and locate an idle core/thread in the LLC cache domain.
6192  */
6193 static int select_idle_sibling(struct task_struct *p, int prev, int target)
6194 {
6195         struct sched_domain *sd;
6196         int i, recent_used_cpu;
6197 
6198         if (available_idle_cpu(target))
6199                 return target;
6200 
6201         /*
6202          * If the previous CPU is cache affine and idle, don't be stupid:
6203          */
6204         if (prev != target && cpus_share_cache(prev, target) && available_idle_cpu(prev))
6205                 return prev;
6206 
6207         /* Check a recently used CPU as a potential idle candidate: */
6208         recent_used_cpu = p->recent_used_cpu;
6209         if (recent_used_cpu != prev &&
6210             recent_used_cpu != target &&
6211             cpus_share_cache(recent_used_cpu, target) &&
6212             available_idle_cpu(recent_used_cpu) &&
6213             cpumask_test_cpu(p->recent_used_cpu, &p->cpus_allowed)) {
6214                 /*
6215                  * Replace recent_used_cpu with prev as it is a potential
6216                  * candidate for the next wake:
6217                  */
6218                 p->recent_used_cpu = prev;
6219                 return recent_used_cpu;
6220         }
6221 
6222         sd = rcu_dereference(per_cpu(sd_llc, target));
6223         if (!sd)
6224                 return target;
6225 
6226         i = select_idle_core(p, sd, target);
6227         if ((unsigned)i < nr_cpumask_bits)
6228                 return i;
6229 
6230         i = select_idle_cpu(p, sd, target);
6231         if ((unsigned)i < nr_cpumask_bits)
6232                 return i;
6233 
6234         i = select_idle_smt(p, sd, target);
6235         if ((unsigned)i < nr_cpumask_bits)
6236                 return i;
6237 
6238         return target;
6239 }
6240 
6241 /**
6242  * Amount of capacity of a CPU that is (estimated to be) used by CFS tasks
6243  * @cpu: the CPU to get the utilization of
6244  *
6245  * The unit of the return value must be the one of capacity so we can compare
6246  * the utilization with the capacity of the CPU that is available for CFS task
6247  * (ie cpu_capacity).
6248  *
6249  * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
6250  * recent utilization of currently non-runnable tasks on a CPU. It represents
6251  * the amount of utilization of a CPU in the range [0..capacity_orig] where
6252  * capacity_orig is the cpu_capacity available at the highest frequency
6253  * (arch_scale_freq_capacity()).
6254  * The utilization of a CPU converges towards a sum equal to or less than the
6255  * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
6256  * the running time on this CPU scaled by capacity_curr.
6257  *
6258  * The estimated utilization of a CPU is defined to be the maximum between its
6259  * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
6260  * currently RUNNABLE on that CPU.
6261  * This allows to properly represent the expected utilization of a CPU which
6262  * has just got a big task running since a long sleep period. At the same time
6263  * however it preserves the benefits of the "blocked utilization" in
6264  * describing the potential for other tasks waking up on the same CPU.
6265  *
6266  * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
6267  * higher than capacity_orig because of unfortunate rounding in
6268  * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
6269  * the average stabilizes with the new running time. We need to check that the
6270  * utilization stays within the range of [0..capacity_orig] and cap it if
6271  * necessary. Without utilization capping, a group could be seen as overloaded
6272  * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
6273  * available capacity. We allow utilization to overshoot capacity_curr (but not
6274  * capacity_orig) as it useful for predicting the capacity required after task
6275  * migrations (scheduler-driven DVFS).
6276  *
6277  * Return: the (estimated) utilization for the specified CPU
6278  */
6279 static inline unsigned long cpu_util(int cpu)
6280 {
6281         struct cfs_rq *cfs_rq;
6282         unsigned int util;
6283 
6284         cfs_rq = &cpu_rq(cpu)->cfs;
6285         util = READ_ONCE(cfs_rq->avg.util_avg);
6286 
6287         if (sched_feat(UTIL_EST))
6288                 util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
6289 
6290         return min_t(unsigned long, util, capacity_orig_of(cpu));
6291 }
6292 
6293 /*
6294  * cpu_util_without: compute cpu utilization without any contributions from *p
6295  * @cpu: the CPU which utilization is requested
6296  * @p: the task which utilization should be discounted
6297  *
6298  * The utilization of a CPU is defined by the utilization of tasks currently
6299  * enqueued on that CPU as well as tasks which are currently sleeping after an
6300  * execution on that CPU.
6301  *
6302  * This method returns the utilization of the specified CPU by discounting the
6303  * utilization of the specified task, whenever the task is currently
6304  * contributing to the CPU utilization.
6305  */
6306 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
6307 {
6308         struct cfs_rq *cfs_rq;
6309         unsigned int util;
6310 
6311         /* Task has no contribution or is new */
6312         if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6313                 return cpu_util(cpu);
6314 
6315         cfs_rq = &cpu_rq(cpu)->cfs;
6316         util = READ_ONCE(cfs_rq->avg.util_avg);
6317 
6318         /* Discount task's util from CPU's util */
6319         lsub_positive(&util, task_util(p));
6320 
6321         /*
6322          * Covered cases:
6323          *
6324          * a) if *p is the only task sleeping on this CPU, then:
6325          *      cpu_util (== task_util) > util_est (== 0)
6326          *    and thus we return:
6327          *      cpu_util_without = (cpu_util - task_util) = 0
6328          *
6329          * b) if other tasks are SLEEPING on this CPU, which is now exiting
6330          *    IDLE, then:
6331          *      cpu_util >= task_util
6332          *      cpu_util > util_est (== 0)
6333          *    and thus we discount *p's blocked utilization to return:
6334          *      cpu_util_without = (cpu_util - task_util) >= 0
6335          *
6336          * c) if other tasks are RUNNABLE on that CPU and
6337          *      util_est > cpu_util
6338          *    then we use util_est since it returns a more restrictive
6339          *    estimation of the spare capacity on that CPU, by just
6340          *    considering the expected utilization of tasks already
6341          *    runnable on that CPU.
6342          *
6343          * Cases a) and b) are covered by the above code, while case c) is
6344          * covered by the following code when estimated utilization is
6345          * enabled.
6346          */
6347         if (sched_feat(UTIL_EST)) {
6348                 unsigned int estimated =
6349                         READ_ONCE(cfs_rq->avg.util_est.enqueued);
6350 
6351                 /*
6352                  * Despite the following checks we still have a small window
6353                  * for a possible race, when an execl's select_task_rq_fair()
6354                  * races with LB's detach_task():
6355                  *
6356                  *   detach_task()
6357                  *     p->on_rq = TASK_ON_RQ_MIGRATING;
6358                  *     ---------------------------------- A
6359                  *     deactivate_task()                   \
6360                  *       dequeue_task()                     + RaceTime
6361                  *         util_est_dequeue()              /
6362                  *     ---------------------------------- B
6363                  *
6364                  * The additional check on "current == p" it's required to
6365                  * properly fix the execl regression and it helps in further
6366                  * reducing the chances for the above race.
6367                  */
6368                 if (unlikely(task_on_rq_queued(p) || current == p))
6369                         lsub_positive(&estimated, _task_util_est(p));
6370 
6371                 util = max(util, estimated);
6372         }
6373 
6374         /*
6375          * Utilization (estimated) can exceed the CPU capacity, thus let's
6376          * clamp to the maximum CPU capacity to ensure consistency with
6377          * the cpu_util call.
6378          */
6379         return min_t(unsigned long, util, capacity_orig_of(cpu));
6380 }
6381 
6382 /*
6383  * Disable WAKE_AFFINE in the case where task @p doesn't fit in the
6384  * capacity of either the waking CPU @cpu or the previous CPU @prev_cpu.
6385  *
6386  * In that case WAKE_AFFINE doesn't make sense and we'll let
6387  * BALANCE_WAKE sort things out.
6388  */
6389 static int wake_cap(struct task_struct *p, int cpu, int prev_cpu)
6390 {
6391         long min_cap, max_cap;
6392 
6393         if (!static_branch_unlikely(&sched_asym_cpucapacity))
6394                 return 0;
6395 
6396         min_cap = min(capacity_orig_of(prev_cpu), capacity_orig_of(cpu));
6397         max_cap = cpu_rq(cpu)->rd->max_cpu_capacity;
6398 
6399         /* Minimum capacity is close to max, no need to abort wake_affine */
6400         if (max_cap - min_cap < max_cap >> 3)
6401                 return 0;
6402 
6403         /* Bring task utilization in sync with prev_cpu */
6404         sync_entity_load_avg(&p->se);
6405 
6406         return !task_fits_capacity(p, min_cap);
6407 }
6408 
6409 /*
6410  * Predicts what cpu_util(@cpu) would return if @p was migrated (and enqueued)
6411  * to @dst_cpu.
6412  */
6413 static unsigned long cpu_util_next(int cpu, struct task_struct *p, int dst_cpu)
6414 {
6415         struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
6416         unsigned long util_est, util = READ_ONCE(cfs_rq->avg.util_avg);
6417 
6418         /*
6419          * If @p migrates from @cpu to another, remove its contribution. Or,
6420          * if @p migrates from another CPU to @cpu, add its contribution. In
6421          * the other cases, @cpu is not impacted by the migration, so the
6422          * util_avg should already be correct.
6423          */
6424         if (task_cpu(p) == cpu && dst_cpu != cpu)
6425                 sub_positive(&util, task_util(p));
6426         else if (task_cpu(p) != cpu && dst_cpu == cpu)
6427                 util += task_util(p);
6428 
6429         if (sched_feat(UTIL_EST)) {
6430                 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
6431 
6432                 /*
6433                  * During wake-up, the task isn't enqueued yet and doesn't
6434                  * appear in the cfs_rq->avg.util_est.enqueued of any rq,
6435                  * so just add it (if needed) to "simulate" what will be
6436                  * cpu_util() after the task has been enqueued.
6437                  */
6438                 if (dst_cpu == cpu)
6439                         util_est += _task_util_est(p);
6440 
6441                 util = max(util, util_est);
6442         }
6443 
6444         return min(util, capacity_orig_of(cpu));
6445 }
6446 
6447 /*
6448  * compute_energy(): Estimates the energy that would be consumed if @p was
6449  * migrated to @dst_cpu. compute_energy() predicts what will be the utilization
6450  * landscape of the * CPUs after the task migration, and uses the Energy Model
6451  * to compute what would be the energy if we decided to actually migrate that
6452  * task.
6453  */
6454 static long
6455 compute_energy(struct task_struct *p, int dst_cpu, struct perf_domain *pd)
6456 {
6457         long util, max_util, sum_util, energy = 0;
6458         int cpu;
6459 
6460         for (; pd; pd = pd->next) {
6461                 max_util = sum_util = 0;
6462                 /*
6463                  * The capacity state of CPUs of the current rd can be driven by
6464                  * CPUs of another rd if they belong to the same performance
6465                  * domain. So, account for the utilization of these CPUs too
6466                  * by masking pd with cpu_online_mask instead of the rd span.
6467                  *
6468                  * If an entire performance domain is outside of the current rd,
6469                  * it will not appear in its pd list and will not be accounted
6470                  * by compute_energy().
6471                  */
6472                 for_each_cpu_and(cpu, perf_domain_span(pd), cpu_online_mask) {
6473                         util = cpu_util_next(cpu, p, dst_cpu);
6474                         util = schedutil_energy_util(cpu, util);
6475                         max_util = max(util, max_util);
6476                         sum_util += util;
6477                 }
6478 
6479                 energy += em_pd_energy(pd->em_pd, max_util, sum_util);
6480         }
6481 
6482         return energy;
6483 }
6484 
6485 /*
6486  * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
6487  * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
6488  * spare capacity in each performance domain and uses it as a potential
6489  * candidate to execute the task. Then, it uses the Energy Model to figure
6490  * out which of the CPU candidates is the most energy-efficient.
6491  *
6492  * The rationale for this heuristic is as follows. In a performance domain,
6493  * all the most energy efficient CPU candidates (according to the Energy
6494  * Model) are those for which we'll request a low frequency. When there are
6495  * several CPUs for which the frequency request will be the same, we don't
6496  * have enough data to break the tie between them, because the Energy Model
6497  * only includes active power costs. With this model, if we assume that
6498  * frequency requests follow utilization (e.g. using schedutil), the CPU with
6499  * the maximum spare capacity in a performance domain is guaranteed to be among
6500  * the best candidates of the performance domain.
6501  *
6502  * In practice, it could be preferable from an energy standpoint to pack
6503  * small tasks on a CPU in order to let other CPUs go in deeper idle states,
6504  * but that could also hurt our chances to go cluster idle, and we have no
6505  * ways to tell with the current Energy Model if this is actually a good
6506  * idea or not. So, find_energy_efficient_cpu() basically favors
6507  * cluster-packing, and spreading inside a cluster. That should at least be
6508  * a good thing for latency, and this is consistent with the idea that most
6509  * of the energy savings of EAS come from the asymmetry of the system, and
6510  * not so much from breaking the tie between identical CPUs. That's also the
6511  * reason why EAS is enabled in the topology code only for systems where
6512  * SD_ASYM_CPUCAPACITY is set.
6513  *
6514  * NOTE: Forkees are not accepted in the energy-aware wake-up path because
6515  * they don't have any useful utilization data yet and it's not possible to
6516  * forecast their impact on energy consumption. Consequently, they will be
6517  * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
6518  * to be energy-inefficient in some use-cases. The alternative would be to
6519  * bias new tasks towards specific types of CPUs first, or to try to infer
6520  * their util_avg from the parent task, but those heuristics could hurt
6521  * other use-cases too. So, until someone finds a better way to solve this,
6522  * let's keep things simple by re-using the existing slow path.
6523  */
6524 
6525 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
6526 {
6527         unsigned long prev_energy = ULONG_MAX, best_energy = ULONG_MAX;
6528         struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
6529         int cpu, best_energy_cpu = prev_cpu;
6530         struct perf_domain *head, *pd;
6531         unsigned long cpu_cap, util;
6532         struct sched_domain *sd;
6533 
6534         rcu_read_lock();
6535         pd = rcu_dereference(rd->pd);
6536         if (!pd || READ_ONCE(rd->overutilized))
6537                 goto fail;
6538         head = pd;
6539 
6540         /*
6541          * Energy-aware wake-up happens on the lowest sched_domain starting
6542          * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
6543          */
6544         sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
6545         while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
6546                 sd = sd->parent;
6547         if (!sd)
6548                 goto fail;
6549 
6550         sync_entity_load_avg(&p->se);
6551         if (!task_util_est(p))
6552                 goto unlock;
6553 
6554         for (; pd; pd = pd->next) {
6555                 unsigned long cur_energy, spare_cap, max_spare_cap = 0;
6556                 int max_spare_cap_cpu = -1;
6557 
6558                 for_each_cpu_and(cpu, perf_domain_span(pd), sched_domain_span(sd)) {
6559                         if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
6560                                 continue;
6561 
6562                         /* Skip CPUs that will be overutilized. */
6563                         util = cpu_util_next(cpu, p, cpu);
6564                         cpu_cap = capacity_of(cpu);
6565                         if (cpu_cap * 1024 < util * capacity_margin)
6566                                 continue;
6567 
6568                         /* Always use prev_cpu as a candidate. */
6569                         if (cpu == prev_cpu) {
6570                                 prev_energy = compute_energy(p, prev_cpu, head);
6571                                 best_energy = min(best_energy, prev_energy);
6572                                 continue;
6573                         }
6574 
6575                         /*
6576                          * Find the CPU with the maximum spare capacity in
6577                          * the performance domain
6578                          */
6579                         spare_cap = cpu_cap - util;
6580                         if (spare_cap > max_spare_cap) {
6581                                 max_spare_cap = spare_cap;
6582                                 max_spare_cap_cpu = cpu;
6583                         }
6584                 }
6585 
6586                 /* Evaluate the energy impact of using this CPU. */
6587                 if (max_spare_cap_cpu >= 0) {
6588                         cur_energy = compute_energy(p, max_spare_cap_cpu, head);
6589                         if (cur_energy < best_energy) {
6590                                 best_energy = cur_energy;
6591                                 best_energy_cpu = max_spare_cap_cpu;
6592                         }
6593                 }
6594         }
6595 unlock:
6596         rcu_read_unlock();
6597 
6598         /*
6599          * Pick the best CPU if prev_cpu cannot be used, or if it saves at
6600          * least 6% of the energy used by prev_cpu.
6601          */
6602         if (prev_energy == ULONG_MAX)
6603                 return best_energy_cpu;
6604 
6605         if ((prev_energy - best_energy) > (prev_energy >> 4))
6606                 return best_energy_cpu;
6607 
6608         return prev_cpu;
6609 
6610 fail:
6611         rcu_read_unlock();
6612 
6613         return -1;
6614 }
6615 
6616 /*
6617  * select_task_rq_fair: Select target runqueue for the waking task in domains
6618  * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
6619  * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
6620  *
6621  * Balances load by selecting the idlest CPU in the idlest group, or under
6622  * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
6623  *
6624  * Returns the target CPU number.
6625  *
6626  * preempt must be disabled.
6627  */
6628 static int
6629 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
6630 {
6631         struct sched_domain *tmp, *sd = NULL;
6632         int cpu = smp_processor_id();
6633         int new_cpu = prev_cpu;
6634         int want_affine = 0;
6635         int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
6636 
6637         if (sd_flag & SD_BALANCE_WAKE) {
6638                 record_wakee(p);
6639 
6640                 if (static_branch_unlikely(&sched_energy_present)) {
6641                         new_cpu = find_energy_efficient_cpu(p, prev_cpu);
6642                         if (new_cpu >= 0)
6643                                 return new_cpu;
6644                         new_cpu = prev_cpu;
6645                 }
6646 
6647                 want_affine = !wake_wide(p) && !wake_cap(p, cpu, prev_cpu) &&
6648                               cpumask_test_cpu(cpu, &p->cpus_allowed);
6649         }
6650 
6651         rcu_read_lock();
6652         for_each_domain(cpu, tmp) {
6653                 if (!(tmp->flags & SD_LOAD_BALANCE))
6654                         break;
6655 
6656                 /*
6657                  * If both 'cpu' and 'prev_cpu' are part of this domain,
6658                  * cpu is a valid SD_WAKE_AFFINE target.
6659                  */
6660                 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
6661                     cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
6662                         if (cpu != prev_cpu)
6663                                 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
6664 
6665                         sd = NULL; /* Prefer wake_affine over balance flags */
6666                         break;
6667                 }
6668 
6669                 if (tmp->flags & sd_flag)
6670                         sd = tmp;
6671                 else if (!want_affine)
6672                         break;
6673         }
6674 
6675         if (unlikely(sd)) {
6676                 /* Slow path */
6677                 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
6678         } else if (sd_flag & SD_BALANCE_WAKE) { /* XXX always ? */
6679                 /* Fast path */
6680 
6681                 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
6682 
6683                 if (want_affine)
6684                         current->recent_used_cpu = cpu;
6685         }
6686         rcu_read_unlock();
6687 
6688         return new_cpu;
6689 }
6690 
6691 static void detach_entity_cfs_rq(struct sched_entity *se);
6692 
6693 /*
6694  * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
6695  * cfs_rq_of(p) references at time of call are still valid and identify the
6696  * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
6697  */
6698 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
6699 {
6700         /*
6701          * As blocked tasks retain absolute vruntime the migration needs to
6702          * deal with this by subtracting the old and adding the new
6703          * min_vruntime -- the latter is done by enqueue_entity() when placing
6704          * the task on the new runqueue.
6705          */
6706         if (p->state == TASK_WAKING) {
6707                 struct sched_entity *se = &p->se;
6708                 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6709                 u64 min_vruntime;
6710 
6711 #ifndef CONFIG_64BIT
6712                 u64 min_vruntime_copy;
6713 
6714                 do {
6715                         min_vruntime_copy = cfs_rq->min_vruntime_copy;
6716                         smp_rmb();
6717                         min_vruntime = cfs_rq->min_vruntime;
6718                 } while (min_vruntime != min_vruntime_copy);
6719 #else
6720                 min_vruntime = cfs_rq->min_vruntime;
6721 #endif
6722 
6723                 se->vruntime -= min_vruntime;
6724         }
6725 
6726         if (p->on_rq == TASK_ON_RQ_MIGRATING) {
6727                 /*
6728                  * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
6729                  * rq->lock and can modify state directly.
6730                  */
6731                 lockdep_assert_held(&task_rq(p)->lock);
6732                 detach_entity_cfs_rq(&p->se);
6733 
6734         } else {
6735                 /*
6736                  * We are supposed to update the task to "current" time, then
6737                  * its up to date and ready to go to new CPU/cfs_rq. But we
6738                  * have difficulty in getting what current time is, so simply
6739                  * throw away the out-of-date time. This will result in the
6740                  * wakee task is less decayed, but giving the wakee more load
6741                  * sounds not bad.
6742                  */
6743                 remove_entity_load_avg(&p->se);
6744         }
6745 
6746         /* Tell new CPU we are migrated */
6747         p->se.avg.last_update_time = 0;
6748 
6749         /* We have migrated, no longer consider this task hot */
6750         p->se.exec_start = 0;
6751 
6752         update_scan_period(p, new_cpu);
6753 }
6754 
6755 static void task_dead_fair(struct task_struct *p)
6756 {
6757         remove_entity_load_avg(&p->se);
6758 }
6759 #endif /* CONFIG_SMP */
6760 
6761 static unsigned long wakeup_gran(struct sched_entity *se)
6762 {
6763         unsigned long gran = sysctl_sched_wakeup_granularity;
6764 
6765         /*
6766          * Since its curr running now, convert the gran from real-time
6767          * to virtual-time in his units.
6768          *
6769          * By using 'se' instead of 'curr' we penalize light tasks, so
6770          * they get preempted easier. That is, if 'se' < 'curr' then
6771          * the resulting gran will be larger, therefore penalizing the
6772          * lighter, if otoh 'se' > 'curr' then the resulting gran will
6773          * be smaller, again penalizing the lighter task.
6774          *
6775          * This is especially important for buddies when the leftmost
6776          * task is higher priority than the buddy.
6777          */
6778         return calc_delta_fair(gran, se);
6779 }
6780 
6781 /*
6782  * Should 'se' preempt 'curr'.
6783  *
6784  *             |s1
6785  *        |s2
6786  *   |s3
6787  *         g
6788  *      |<--->|c
6789  *
6790  *  w(c, s1) = -1
6791  *  w(c, s2) =  0
6792  *  w(c, s3) =  1
6793  *
6794  */
6795 static int
6796 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
6797 {
6798         s64 gran, vdiff = curr->vruntime - se->vruntime;
6799 
6800         if (vdiff <= 0)
6801                 return -1;
6802 
6803         gran = wakeup_gran(se);
6804         if (vdiff > gran)
6805                 return 1;
6806 
6807         return 0;
6808 }
6809 
6810 static void set_last_buddy(struct sched_entity *se)
6811 {
6812         if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
6813                 return;
6814 
6815         for_each_sched_entity(se) {
6816                 if (SCHED_WARN_ON(!se->on_rq))
6817                         return;
6818                 cfs_rq_of(se)->last = se;
6819         }
6820 }
6821 
6822 static void set_next_buddy(struct sched_entity *se)
6823 {
6824         if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
6825                 return;
6826 
6827         for_each_sched_entity(se) {
6828                 if (SCHED_WARN_ON(!se->on_rq))
6829                         return;
6830                 cfs_rq_of(se)->next = se;
6831         }
6832 }
6833 
6834 static void set_skip_buddy(struct sched_entity *se)
6835 {
6836         for_each_sched_entity(se)
6837                 cfs_rq_of(se)->skip = se;
6838 }
6839 
6840 /*
6841  * Preempt the current task with a newly woken task if needed:
6842  */
6843 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
6844 {
6845         struct task_struct *curr = rq->curr;
6846         struct sched_entity *se = &curr->se, *pse = &p->se;
6847         struct cfs_rq *cfs_rq = task_cfs_rq(curr);
6848         int scale = cfs_rq->nr_running >= sched_nr_latency;
6849         int next_buddy_marked = 0;
6850 
6851         if (unlikely(se == pse))
6852                 return;
6853 
6854         /*
6855          * This is possible from callers such as attach_tasks(), in which we
6856          * unconditionally check_prempt_curr() after an enqueue (which may have
6857          * lead to a throttle).  This both saves work and prevents false
6858          * next-buddy nomination below.
6859          */
6860         if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
6861                 return;
6862 
6863         if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
6864                 set_next_buddy(pse);
6865                 next_buddy_marked = 1;
6866         }
6867 
6868         /*
6869          * We can come here with TIF_NEED_RESCHED already set from new task
6870          * wake up path.
6871          *
6872          * Note: this also catches the edge-case of curr being in a throttled
6873          * group (e.g. via set_curr_task), since update_curr() (in the
6874          * enqueue of curr) will have resulted in resched being set.  This
6875          * prevents us from potentially nominating it as a false LAST_BUDDY
6876          * below.
6877          */
6878         if (test_tsk_need_resched(curr))
6879                 return;
6880 
6881         /* Idle tasks are by definition preempted by non-idle tasks. */
6882         if (unlikely(task_has_idle_policy(curr)) &&
6883             likely(!task_has_idle_policy(p)))
6884                 goto preempt;
6885 
6886         /*
6887          * Batch and idle tasks do not preempt non-idle tasks (their preemption
6888          * is driven by the tick):
6889          */
6890         if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
6891                 return;
6892 
6893         find_matching_se(&se, &pse);
6894         update_curr(cfs_rq_of(se));
6895         BUG_ON(!pse);
6896         if (wakeup_preempt_entity(se, pse) == 1) {
6897                 /*
6898                  * Bias pick_next to pick the sched entity that is
6899                  * triggering this preemption.
6900                  */
6901                 if (!next_buddy_marked)
6902                         set_next_buddy(pse);
6903                 goto preempt;
6904         }
6905 
6906         return;
6907 
6908 preempt:
6909         resched_curr(rq);
6910         /*
6911          * Only set the backward buddy when the current task is still
6912          * on the rq. This can happen when a wakeup gets interleaved
6913          * with schedule on the ->pre_schedule() or idle_balance()
6914          * point, either of which can * drop the rq lock.
6915          *
6916          * Also, during early boot the idle thread is in the fair class,
6917          * for obvious reasons its a bad idea to schedule back to it.
6918          */
6919         if (unlikely(!se->on_rq || curr == rq->idle))
6920                 return;
6921 
6922         if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
6923                 set_last_buddy(se);
6924 }
6925 
6926 static struct task_struct *
6927 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
6928 {
6929         struct cfs_rq *cfs_rq = &rq->cfs;
6930         struct sched_entity *se;
6931         struct task_struct *p;
6932         int new_tasks;
6933 
6934 again:
6935         if (!cfs_rq->nr_running)
6936                 goto idle;
6937 
6938 #ifdef CONFIG_FAIR_GROUP_SCHED
6939         if (prev->sched_class != &fair_sched_class)
6940                 goto simple;
6941 
6942         /*
6943          * Because of the set_next_buddy() in dequeue_task_fair() it is rather
6944          * likely that a next task is from the same cgroup as the current.
6945          *
6946          * Therefore attempt to avoid putting and setting the entire cgroup
6947          * hierarchy, only change the part that actually changes.
6948          */
6949 
6950         do {
6951                 struct sched_entity *curr = cfs_rq->curr;
6952 
6953                 /*
6954                  * Since we got here without doing put_prev_entity() we also
6955                  * have to consider cfs_rq->curr. If it is still a runnable
6956                  * entity, update_curr() will update its vruntime, otherwise
6957                  * forget we've ever seen it.
6958                  */
6959                 if (curr) {
6960                         if (curr->on_rq)
6961                                 update_curr(cfs_rq);
6962                         else
6963                                 curr = NULL;
6964 
6965                         /*
6966                          * This call to check_cfs_rq_runtime() will do the
6967                          * throttle and dequeue its entity in the parent(s).
6968                          * Therefore the nr_running test will indeed
6969                          * be correct.
6970                          */
6971                         if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
6972                                 cfs_rq = &rq->cfs;
6973 
6974                                 if (!cfs_rq->nr_running)
6975                                         goto idle;
6976 
6977                                 goto simple;
6978                         }
6979                 }
6980 
6981                 se = pick_next_entity(cfs_rq, curr);
6982                 cfs_rq = group_cfs_rq(se);
6983         } while (cfs_rq);
6984 
6985         p = task_of(se);
6986 
6987         /*
6988          * Since we haven't yet done put_prev_entity and if the selected task
6989          *