Merge branch 'for-4.14-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
[sfrench/cifs-2.6.git] / kernel / sched / topology.c
1 /*
2  * Scheduler topology setup/handling methods
3  */
4 #include <linux/sched.h>
5 #include <linux/mutex.h>
6
7 #include "sched.h"
8
9 DEFINE_MUTEX(sched_domains_mutex);
10
11 /* Protected by sched_domains_mutex: */
12 cpumask_var_t sched_domains_tmpmask;
13 cpumask_var_t sched_domains_tmpmask2;
14
15 #ifdef CONFIG_SCHED_DEBUG
16
17 static int __init sched_debug_setup(char *str)
18 {
19         sched_debug_enabled = true;
20
21         return 0;
22 }
23 early_param("sched_debug", sched_debug_setup);
24
25 static inline bool sched_debug(void)
26 {
27         return sched_debug_enabled;
28 }
29
30 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
31                                   struct cpumask *groupmask)
32 {
33         struct sched_group *group = sd->groups;
34
35         cpumask_clear(groupmask);
36
37         printk(KERN_DEBUG "%*s domain-%d: ", level, "", level);
38
39         if (!(sd->flags & SD_LOAD_BALANCE)) {
40                 printk("does not load-balance\n");
41                 if (sd->parent)
42                         printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
43                                         " has parent");
44                 return -1;
45         }
46
47         printk(KERN_CONT "span=%*pbl level=%s\n",
48                cpumask_pr_args(sched_domain_span(sd)), sd->name);
49
50         if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
51                 printk(KERN_ERR "ERROR: domain->span does not contain "
52                                 "CPU%d\n", cpu);
53         }
54         if (!cpumask_test_cpu(cpu, sched_group_span(group))) {
55                 printk(KERN_ERR "ERROR: domain->groups does not contain"
56                                 " CPU%d\n", cpu);
57         }
58
59         printk(KERN_DEBUG "%*s groups:", level + 1, "");
60         do {
61                 if (!group) {
62                         printk("\n");
63                         printk(KERN_ERR "ERROR: group is NULL\n");
64                         break;
65                 }
66
67                 if (!cpumask_weight(sched_group_span(group))) {
68                         printk(KERN_CONT "\n");
69                         printk(KERN_ERR "ERROR: empty group\n");
70                         break;
71                 }
72
73                 if (!(sd->flags & SD_OVERLAP) &&
74                     cpumask_intersects(groupmask, sched_group_span(group))) {
75                         printk(KERN_CONT "\n");
76                         printk(KERN_ERR "ERROR: repeated CPUs\n");
77                         break;
78                 }
79
80                 cpumask_or(groupmask, groupmask, sched_group_span(group));
81
82                 printk(KERN_CONT " %d:{ span=%*pbl",
83                                 group->sgc->id,
84                                 cpumask_pr_args(sched_group_span(group)));
85
86                 if ((sd->flags & SD_OVERLAP) &&
87                     !cpumask_equal(group_balance_mask(group), sched_group_span(group))) {
88                         printk(KERN_CONT " mask=%*pbl",
89                                 cpumask_pr_args(group_balance_mask(group)));
90                 }
91
92                 if (group->sgc->capacity != SCHED_CAPACITY_SCALE)
93                         printk(KERN_CONT " cap=%lu", group->sgc->capacity);
94
95                 if (group == sd->groups && sd->child &&
96                     !cpumask_equal(sched_domain_span(sd->child),
97                                    sched_group_span(group))) {
98                         printk(KERN_ERR "ERROR: domain->groups does not match domain->child\n");
99                 }
100
101                 printk(KERN_CONT " }");
102
103                 group = group->next;
104
105                 if (group != sd->groups)
106                         printk(KERN_CONT ",");
107
108         } while (group != sd->groups);
109         printk(KERN_CONT "\n");
110
111         if (!cpumask_equal(sched_domain_span(sd), groupmask))
112                 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
113
114         if (sd->parent &&
115             !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
116                 printk(KERN_ERR "ERROR: parent span is not a superset "
117                         "of domain->span\n");
118         return 0;
119 }
120
121 static void sched_domain_debug(struct sched_domain *sd, int cpu)
122 {
123         int level = 0;
124
125         if (!sched_debug_enabled)
126                 return;
127
128         if (!sd) {
129                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
130                 return;
131         }
132
133         printk(KERN_DEBUG "CPU%d attaching sched-domain(s):\n", cpu);
134
135         for (;;) {
136                 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
137                         break;
138                 level++;
139                 sd = sd->parent;
140                 if (!sd)
141                         break;
142         }
143 }
144 #else /* !CONFIG_SCHED_DEBUG */
145
146 # define sched_debug_enabled 0
147 # define sched_domain_debug(sd, cpu) do { } while (0)
148 static inline bool sched_debug(void)
149 {
150         return false;
151 }
152 #endif /* CONFIG_SCHED_DEBUG */
153
154 static int sd_degenerate(struct sched_domain *sd)
155 {
156         if (cpumask_weight(sched_domain_span(sd)) == 1)
157                 return 1;
158
159         /* Following flags need at least 2 groups */
160         if (sd->flags & (SD_LOAD_BALANCE |
161                          SD_BALANCE_NEWIDLE |
162                          SD_BALANCE_FORK |
163                          SD_BALANCE_EXEC |
164                          SD_SHARE_CPUCAPACITY |
165                          SD_ASYM_CPUCAPACITY |
166                          SD_SHARE_PKG_RESOURCES |
167                          SD_SHARE_POWERDOMAIN)) {
168                 if (sd->groups != sd->groups->next)
169                         return 0;
170         }
171
172         /* Following flags don't use groups */
173         if (sd->flags & (SD_WAKE_AFFINE))
174                 return 0;
175
176         return 1;
177 }
178
179 static int
180 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
181 {
182         unsigned long cflags = sd->flags, pflags = parent->flags;
183
184         if (sd_degenerate(parent))
185                 return 1;
186
187         if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
188                 return 0;
189
190         /* Flags needing groups don't count if only 1 group in parent */
191         if (parent->groups == parent->groups->next) {
192                 pflags &= ~(SD_LOAD_BALANCE |
193                                 SD_BALANCE_NEWIDLE |
194                                 SD_BALANCE_FORK |
195                                 SD_BALANCE_EXEC |
196                                 SD_ASYM_CPUCAPACITY |
197                                 SD_SHARE_CPUCAPACITY |
198                                 SD_SHARE_PKG_RESOURCES |
199                                 SD_PREFER_SIBLING |
200                                 SD_SHARE_POWERDOMAIN);
201                 if (nr_node_ids == 1)
202                         pflags &= ~SD_SERIALIZE;
203         }
204         if (~cflags & pflags)
205                 return 0;
206
207         return 1;
208 }
209
210 static void free_rootdomain(struct rcu_head *rcu)
211 {
212         struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
213
214         cpupri_cleanup(&rd->cpupri);
215         cpudl_cleanup(&rd->cpudl);
216         free_cpumask_var(rd->dlo_mask);
217         free_cpumask_var(rd->rto_mask);
218         free_cpumask_var(rd->online);
219         free_cpumask_var(rd->span);
220         kfree(rd);
221 }
222
223 void rq_attach_root(struct rq *rq, struct root_domain *rd)
224 {
225         struct root_domain *old_rd = NULL;
226         unsigned long flags;
227
228         raw_spin_lock_irqsave(&rq->lock, flags);
229
230         if (rq->rd) {
231                 old_rd = rq->rd;
232
233                 if (cpumask_test_cpu(rq->cpu, old_rd->online))
234                         set_rq_offline(rq);
235
236                 cpumask_clear_cpu(rq->cpu, old_rd->span);
237
238                 /*
239                  * If we dont want to free the old_rd yet then
240                  * set old_rd to NULL to skip the freeing later
241                  * in this function:
242                  */
243                 if (!atomic_dec_and_test(&old_rd->refcount))
244                         old_rd = NULL;
245         }
246
247         atomic_inc(&rd->refcount);
248         rq->rd = rd;
249
250         cpumask_set_cpu(rq->cpu, rd->span);
251         if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
252                 set_rq_online(rq);
253
254         raw_spin_unlock_irqrestore(&rq->lock, flags);
255
256         if (old_rd)
257                 call_rcu_sched(&old_rd->rcu, free_rootdomain);
258 }
259
260 static int init_rootdomain(struct root_domain *rd)
261 {
262         if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
263                 goto out;
264         if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
265                 goto free_span;
266         if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
267                 goto free_online;
268         if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
269                 goto free_dlo_mask;
270
271         init_dl_bw(&rd->dl_bw);
272         if (cpudl_init(&rd->cpudl) != 0)
273                 goto free_rto_mask;
274
275         if (cpupri_init(&rd->cpupri) != 0)
276                 goto free_cpudl;
277         return 0;
278
279 free_cpudl:
280         cpudl_cleanup(&rd->cpudl);
281 free_rto_mask:
282         free_cpumask_var(rd->rto_mask);
283 free_dlo_mask:
284         free_cpumask_var(rd->dlo_mask);
285 free_online:
286         free_cpumask_var(rd->online);
287 free_span:
288         free_cpumask_var(rd->span);
289 out:
290         return -ENOMEM;
291 }
292
293 /*
294  * By default the system creates a single root-domain with all CPUs as
295  * members (mimicking the global state we have today).
296  */
297 struct root_domain def_root_domain;
298
299 void init_defrootdomain(void)
300 {
301         init_rootdomain(&def_root_domain);
302
303         atomic_set(&def_root_domain.refcount, 1);
304 }
305
306 static struct root_domain *alloc_rootdomain(void)
307 {
308         struct root_domain *rd;
309
310         rd = kzalloc(sizeof(*rd), GFP_KERNEL);
311         if (!rd)
312                 return NULL;
313
314         if (init_rootdomain(rd) != 0) {
315                 kfree(rd);
316                 return NULL;
317         }
318
319         return rd;
320 }
321
322 static void free_sched_groups(struct sched_group *sg, int free_sgc)
323 {
324         struct sched_group *tmp, *first;
325
326         if (!sg)
327                 return;
328
329         first = sg;
330         do {
331                 tmp = sg->next;
332
333                 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
334                         kfree(sg->sgc);
335
336                 if (atomic_dec_and_test(&sg->ref))
337                         kfree(sg);
338                 sg = tmp;
339         } while (sg != first);
340 }
341
342 static void destroy_sched_domain(struct sched_domain *sd)
343 {
344         /*
345          * A normal sched domain may have multiple group references, an
346          * overlapping domain, having private groups, only one.  Iterate,
347          * dropping group/capacity references, freeing where none remain.
348          */
349         free_sched_groups(sd->groups, 1);
350
351         if (sd->shared && atomic_dec_and_test(&sd->shared->ref))
352                 kfree(sd->shared);
353         kfree(sd);
354 }
355
356 static void destroy_sched_domains_rcu(struct rcu_head *rcu)
357 {
358         struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
359
360         while (sd) {
361                 struct sched_domain *parent = sd->parent;
362                 destroy_sched_domain(sd);
363                 sd = parent;
364         }
365 }
366
367 static void destroy_sched_domains(struct sched_domain *sd)
368 {
369         if (sd)
370                 call_rcu(&sd->rcu, destroy_sched_domains_rcu);
371 }
372
373 /*
374  * Keep a special pointer to the highest sched_domain that has
375  * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
376  * allows us to avoid some pointer chasing select_idle_sibling().
377  *
378  * Also keep a unique ID per domain (we use the first CPU number in
379  * the cpumask of the domain), this allows us to quickly tell if
380  * two CPUs are in the same cache domain, see cpus_share_cache().
381  */
382 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
383 DEFINE_PER_CPU(int, sd_llc_size);
384 DEFINE_PER_CPU(int, sd_llc_id);
385 DEFINE_PER_CPU(struct sched_domain_shared *, sd_llc_shared);
386 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
387 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
388
389 static void update_top_cache_domain(int cpu)
390 {
391         struct sched_domain_shared *sds = NULL;
392         struct sched_domain *sd;
393         int id = cpu;
394         int size = 1;
395
396         sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
397         if (sd) {
398                 id = cpumask_first(sched_domain_span(sd));
399                 size = cpumask_weight(sched_domain_span(sd));
400                 sds = sd->shared;
401         }
402
403         rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
404         per_cpu(sd_llc_size, cpu) = size;
405         per_cpu(sd_llc_id, cpu) = id;
406         rcu_assign_pointer(per_cpu(sd_llc_shared, cpu), sds);
407
408         sd = lowest_flag_domain(cpu, SD_NUMA);
409         rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
410
411         sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
412         rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
413 }
414
415 /*
416  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
417  * hold the hotplug lock.
418  */
419 static void
420 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
421 {
422         struct rq *rq = cpu_rq(cpu);
423         struct sched_domain *tmp;
424
425         /* Remove the sched domains which do not contribute to scheduling. */
426         for (tmp = sd; tmp; ) {
427                 struct sched_domain *parent = tmp->parent;
428                 if (!parent)
429                         break;
430
431                 if (sd_parent_degenerate(tmp, parent)) {
432                         tmp->parent = parent->parent;
433                         if (parent->parent)
434                                 parent->parent->child = tmp;
435                         /*
436                          * Transfer SD_PREFER_SIBLING down in case of a
437                          * degenerate parent; the spans match for this
438                          * so the property transfers.
439                          */
440                         if (parent->flags & SD_PREFER_SIBLING)
441                                 tmp->flags |= SD_PREFER_SIBLING;
442                         destroy_sched_domain(parent);
443                 } else
444                         tmp = tmp->parent;
445         }
446
447         if (sd && sd_degenerate(sd)) {
448                 tmp = sd;
449                 sd = sd->parent;
450                 destroy_sched_domain(tmp);
451                 if (sd)
452                         sd->child = NULL;
453         }
454
455         sched_domain_debug(sd, cpu);
456
457         rq_attach_root(rq, rd);
458         tmp = rq->sd;
459         rcu_assign_pointer(rq->sd, sd);
460         dirty_sched_domain_sysctl(cpu);
461         destroy_sched_domains(tmp);
462
463         update_top_cache_domain(cpu);
464 }
465
466 /* Setup the mask of CPUs configured for isolated domains */
467 static int __init isolated_cpu_setup(char *str)
468 {
469         int ret;
470
471         alloc_bootmem_cpumask_var(&cpu_isolated_map);
472         ret = cpulist_parse(str, cpu_isolated_map);
473         if (ret) {
474                 pr_err("sched: Error, all isolcpus= values must be between 0 and %u\n", nr_cpu_ids);
475                 return 0;
476         }
477         return 1;
478 }
479 __setup("isolcpus=", isolated_cpu_setup);
480
481 struct s_data {
482         struct sched_domain ** __percpu sd;
483         struct root_domain      *rd;
484 };
485
486 enum s_alloc {
487         sa_rootdomain,
488         sa_sd,
489         sa_sd_storage,
490         sa_none,
491 };
492
493 /*
494  * Return the canonical balance CPU for this group, this is the first CPU
495  * of this group that's also in the balance mask.
496  *
497  * The balance mask are all those CPUs that could actually end up at this
498  * group. See build_balance_mask().
499  *
500  * Also see should_we_balance().
501  */
502 int group_balance_cpu(struct sched_group *sg)
503 {
504         return cpumask_first(group_balance_mask(sg));
505 }
506
507
508 /*
509  * NUMA topology (first read the regular topology blurb below)
510  *
511  * Given a node-distance table, for example:
512  *
513  *   node   0   1   2   3
514  *     0:  10  20  30  20
515  *     1:  20  10  20  30
516  *     2:  30  20  10  20
517  *     3:  20  30  20  10
518  *
519  * which represents a 4 node ring topology like:
520  *
521  *   0 ----- 1
522  *   |       |
523  *   |       |
524  *   |       |
525  *   3 ----- 2
526  *
527  * We want to construct domains and groups to represent this. The way we go
528  * about doing this is to build the domains on 'hops'. For each NUMA level we
529  * construct the mask of all nodes reachable in @level hops.
530  *
531  * For the above NUMA topology that gives 3 levels:
532  *
533  * NUMA-2       0-3             0-3             0-3             0-3
534  *  groups:     {0-1,3},{1-3}   {0-2},{0,2-3}   {1-3},{0-1,3}   {0,2-3},{0-2}
535  *
536  * NUMA-1       0-1,3           0-2             1-3             0,2-3
537  *  groups:     {0},{1},{3}     {0},{1},{2}     {1},{2},{3}     {0},{2},{3}
538  *
539  * NUMA-0       0               1               2               3
540  *
541  *
542  * As can be seen; things don't nicely line up as with the regular topology.
543  * When we iterate a domain in child domain chunks some nodes can be
544  * represented multiple times -- hence the "overlap" naming for this part of
545  * the topology.
546  *
547  * In order to minimize this overlap, we only build enough groups to cover the
548  * domain. For instance Node-0 NUMA-2 would only get groups: 0-1,3 and 1-3.
549  *
550  * Because:
551  *
552  *  - the first group of each domain is its child domain; this
553  *    gets us the first 0-1,3
554  *  - the only uncovered node is 2, who's child domain is 1-3.
555  *
556  * However, because of the overlap, computing a unique CPU for each group is
557  * more complicated. Consider for instance the groups of NODE-1 NUMA-2, both
558  * groups include the CPUs of Node-0, while those CPUs would not in fact ever
559  * end up at those groups (they would end up in group: 0-1,3).
560  *
561  * To correct this we have to introduce the group balance mask. This mask
562  * will contain those CPUs in the group that can reach this group given the
563  * (child) domain tree.
564  *
565  * With this we can once again compute balance_cpu and sched_group_capacity
566  * relations.
567  *
568  * XXX include words on how balance_cpu is unique and therefore can be
569  * used for sched_group_capacity links.
570  *
571  *
572  * Another 'interesting' topology is:
573  *
574  *   node   0   1   2   3
575  *     0:  10  20  20  30
576  *     1:  20  10  20  20
577  *     2:  20  20  10  20
578  *     3:  30  20  20  10
579  *
580  * Which looks a little like:
581  *
582  *   0 ----- 1
583  *   |     / |
584  *   |   /   |
585  *   | /     |
586  *   2 ----- 3
587  *
588  * This topology is asymmetric, nodes 1,2 are fully connected, but nodes 0,3
589  * are not.
590  *
591  * This leads to a few particularly weird cases where the sched_domain's are
592  * not of the same number for each cpu. Consider:
593  *
594  * NUMA-2       0-3                                             0-3
595  *  groups:     {0-2},{1-3}                                     {1-3},{0-2}
596  *
597  * NUMA-1       0-2             0-3             0-3             1-3
598  *
599  * NUMA-0       0               1               2               3
600  *
601  */
602
603
604 /*
605  * Build the balance mask; it contains only those CPUs that can arrive at this
606  * group and should be considered to continue balancing.
607  *
608  * We do this during the group creation pass, therefore the group information
609  * isn't complete yet, however since each group represents a (child) domain we
610  * can fully construct this using the sched_domain bits (which are already
611  * complete).
612  */
613 static void
614 build_balance_mask(struct sched_domain *sd, struct sched_group *sg, struct cpumask *mask)
615 {
616         const struct cpumask *sg_span = sched_group_span(sg);
617         struct sd_data *sdd = sd->private;
618         struct sched_domain *sibling;
619         int i;
620
621         cpumask_clear(mask);
622
623         for_each_cpu(i, sg_span) {
624                 sibling = *per_cpu_ptr(sdd->sd, i);
625
626                 /*
627                  * Can happen in the asymmetric case, where these siblings are
628                  * unused. The mask will not be empty because those CPUs that
629                  * do have the top domain _should_ span the domain.
630                  */
631                 if (!sibling->child)
632                         continue;
633
634                 /* If we would not end up here, we can't continue from here */
635                 if (!cpumask_equal(sg_span, sched_domain_span(sibling->child)))
636                         continue;
637
638                 cpumask_set_cpu(i, mask);
639         }
640
641         /* We must not have empty masks here */
642         WARN_ON_ONCE(cpumask_empty(mask));
643 }
644
645 /*
646  * XXX: This creates per-node group entries; since the load-balancer will
647  * immediately access remote memory to construct this group's load-balance
648  * statistics having the groups node local is of dubious benefit.
649  */
650 static struct sched_group *
651 build_group_from_child_sched_domain(struct sched_domain *sd, int cpu)
652 {
653         struct sched_group *sg;
654         struct cpumask *sg_span;
655
656         sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
657                         GFP_KERNEL, cpu_to_node(cpu));
658
659         if (!sg)
660                 return NULL;
661
662         sg_span = sched_group_span(sg);
663         if (sd->child)
664                 cpumask_copy(sg_span, sched_domain_span(sd->child));
665         else
666                 cpumask_copy(sg_span, sched_domain_span(sd));
667
668         atomic_inc(&sg->ref);
669         return sg;
670 }
671
672 static void init_overlap_sched_group(struct sched_domain *sd,
673                                      struct sched_group *sg)
674 {
675         struct cpumask *mask = sched_domains_tmpmask2;
676         struct sd_data *sdd = sd->private;
677         struct cpumask *sg_span;
678         int cpu;
679
680         build_balance_mask(sd, sg, mask);
681         cpu = cpumask_first_and(sched_group_span(sg), mask);
682
683         sg->sgc = *per_cpu_ptr(sdd->sgc, cpu);
684         if (atomic_inc_return(&sg->sgc->ref) == 1)
685                 cpumask_copy(group_balance_mask(sg), mask);
686         else
687                 WARN_ON_ONCE(!cpumask_equal(group_balance_mask(sg), mask));
688
689         /*
690          * Initialize sgc->capacity such that even if we mess up the
691          * domains and no possible iteration will get us here, we won't
692          * die on a /0 trap.
693          */
694         sg_span = sched_group_span(sg);
695         sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
696         sg->sgc->min_capacity = SCHED_CAPACITY_SCALE;
697 }
698
699 static int
700 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
701 {
702         struct sched_group *first = NULL, *last = NULL, *sg;
703         const struct cpumask *span = sched_domain_span(sd);
704         struct cpumask *covered = sched_domains_tmpmask;
705         struct sd_data *sdd = sd->private;
706         struct sched_domain *sibling;
707         int i;
708
709         cpumask_clear(covered);
710
711         for_each_cpu_wrap(i, span, cpu) {
712                 struct cpumask *sg_span;
713
714                 if (cpumask_test_cpu(i, covered))
715                         continue;
716
717                 sibling = *per_cpu_ptr(sdd->sd, i);
718
719                 /*
720                  * Asymmetric node setups can result in situations where the
721                  * domain tree is of unequal depth, make sure to skip domains
722                  * that already cover the entire range.
723                  *
724                  * In that case build_sched_domains() will have terminated the
725                  * iteration early and our sibling sd spans will be empty.
726                  * Domains should always include the CPU they're built on, so
727                  * check that.
728                  */
729                 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
730                         continue;
731
732                 sg = build_group_from_child_sched_domain(sibling, cpu);
733                 if (!sg)
734                         goto fail;
735
736                 sg_span = sched_group_span(sg);
737                 cpumask_or(covered, covered, sg_span);
738
739                 init_overlap_sched_group(sd, sg);
740
741                 if (!first)
742                         first = sg;
743                 if (last)
744                         last->next = sg;
745                 last = sg;
746                 last->next = first;
747         }
748         sd->groups = first;
749
750         return 0;
751
752 fail:
753         free_sched_groups(first, 0);
754
755         return -ENOMEM;
756 }
757
758
759 /*
760  * Package topology (also see the load-balance blurb in fair.c)
761  *
762  * The scheduler builds a tree structure to represent a number of important
763  * topology features. By default (default_topology[]) these include:
764  *
765  *  - Simultaneous multithreading (SMT)
766  *  - Multi-Core Cache (MC)
767  *  - Package (DIE)
768  *
769  * Where the last one more or less denotes everything up to a NUMA node.
770  *
771  * The tree consists of 3 primary data structures:
772  *
773  *      sched_domain -> sched_group -> sched_group_capacity
774  *          ^ ^             ^ ^
775  *          `-'             `-'
776  *
777  * The sched_domains are per-cpu and have a two way link (parent & child) and
778  * denote the ever growing mask of CPUs belonging to that level of topology.
779  *
780  * Each sched_domain has a circular (double) linked list of sched_group's, each
781  * denoting the domains of the level below (or individual CPUs in case of the
782  * first domain level). The sched_group linked by a sched_domain includes the
783  * CPU of that sched_domain [*].
784  *
785  * Take for instance a 2 threaded, 2 core, 2 cache cluster part:
786  *
787  * CPU   0   1   2   3   4   5   6   7
788  *
789  * DIE  [                             ]
790  * MC   [             ] [             ]
791  * SMT  [     ] [     ] [     ] [     ]
792  *
793  *  - or -
794  *
795  * DIE  0-7 0-7 0-7 0-7 0-7 0-7 0-7 0-7
796  * MC   0-3 0-3 0-3 0-3 4-7 4-7 4-7 4-7
797  * SMT  0-1 0-1 2-3 2-3 4-5 4-5 6-7 6-7
798  *
799  * CPU   0   1   2   3   4   5   6   7
800  *
801  * One way to think about it is: sched_domain moves you up and down among these
802  * topology levels, while sched_group moves you sideways through it, at child
803  * domain granularity.
804  *
805  * sched_group_capacity ensures each unique sched_group has shared storage.
806  *
807  * There are two related construction problems, both require a CPU that
808  * uniquely identify each group (for a given domain):
809  *
810  *  - The first is the balance_cpu (see should_we_balance() and the
811  *    load-balance blub in fair.c); for each group we only want 1 CPU to
812  *    continue balancing at a higher domain.
813  *
814  *  - The second is the sched_group_capacity; we want all identical groups
815  *    to share a single sched_group_capacity.
816  *
817  * Since these topologies are exclusive by construction. That is, its
818  * impossible for an SMT thread to belong to multiple cores, and cores to
819  * be part of multiple caches. There is a very clear and unique location
820  * for each CPU in the hierarchy.
821  *
822  * Therefore computing a unique CPU for each group is trivial (the iteration
823  * mask is redundant and set all 1s; all CPUs in a group will end up at _that_
824  * group), we can simply pick the first CPU in each group.
825  *
826  *
827  * [*] in other words, the first group of each domain is its child domain.
828  */
829
830 static struct sched_group *get_group(int cpu, struct sd_data *sdd)
831 {
832         struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
833         struct sched_domain *child = sd->child;
834         struct sched_group *sg;
835
836         if (child)
837                 cpu = cpumask_first(sched_domain_span(child));
838
839         sg = *per_cpu_ptr(sdd->sg, cpu);
840         sg->sgc = *per_cpu_ptr(sdd->sgc, cpu);
841
842         /* For claim_allocations: */
843         atomic_inc(&sg->ref);
844         atomic_inc(&sg->sgc->ref);
845
846         if (child) {
847                 cpumask_copy(sched_group_span(sg), sched_domain_span(child));
848                 cpumask_copy(group_balance_mask(sg), sched_group_span(sg));
849         } else {
850                 cpumask_set_cpu(cpu, sched_group_span(sg));
851                 cpumask_set_cpu(cpu, group_balance_mask(sg));
852         }
853
854         sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sched_group_span(sg));
855         sg->sgc->min_capacity = SCHED_CAPACITY_SCALE;
856
857         return sg;
858 }
859
860 /*
861  * build_sched_groups will build a circular linked list of the groups
862  * covered by the given span, and will set each group's ->cpumask correctly,
863  * and ->cpu_capacity to 0.
864  *
865  * Assumes the sched_domain tree is fully constructed
866  */
867 static int
868 build_sched_groups(struct sched_domain *sd, int cpu)
869 {
870         struct sched_group *first = NULL, *last = NULL;
871         struct sd_data *sdd = sd->private;
872         const struct cpumask *span = sched_domain_span(sd);
873         struct cpumask *covered;
874         int i;
875
876         lockdep_assert_held(&sched_domains_mutex);
877         covered = sched_domains_tmpmask;
878
879         cpumask_clear(covered);
880
881         for_each_cpu_wrap(i, span, cpu) {
882                 struct sched_group *sg;
883
884                 if (cpumask_test_cpu(i, covered))
885                         continue;
886
887                 sg = get_group(i, sdd);
888
889                 cpumask_or(covered, covered, sched_group_span(sg));
890
891                 if (!first)
892                         first = sg;
893                 if (last)
894                         last->next = sg;
895                 last = sg;
896         }
897         last->next = first;
898         sd->groups = first;
899
900         return 0;
901 }
902
903 /*
904  * Initialize sched groups cpu_capacity.
905  *
906  * cpu_capacity indicates the capacity of sched group, which is used while
907  * distributing the load between different sched groups in a sched domain.
908  * Typically cpu_capacity for all the groups in a sched domain will be same
909  * unless there are asymmetries in the topology. If there are asymmetries,
910  * group having more cpu_capacity will pickup more load compared to the
911  * group having less cpu_capacity.
912  */
913 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
914 {
915         struct sched_group *sg = sd->groups;
916
917         WARN_ON(!sg);
918
919         do {
920                 int cpu, max_cpu = -1;
921
922                 sg->group_weight = cpumask_weight(sched_group_span(sg));
923
924                 if (!(sd->flags & SD_ASYM_PACKING))
925                         goto next;
926
927                 for_each_cpu(cpu, sched_group_span(sg)) {
928                         if (max_cpu < 0)
929                                 max_cpu = cpu;
930                         else if (sched_asym_prefer(cpu, max_cpu))
931                                 max_cpu = cpu;
932                 }
933                 sg->asym_prefer_cpu = max_cpu;
934
935 next:
936                 sg = sg->next;
937         } while (sg != sd->groups);
938
939         if (cpu != group_balance_cpu(sg))
940                 return;
941
942         update_group_capacity(sd, cpu);
943 }
944
945 /*
946  * Initializers for schedule domains
947  * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
948  */
949
950 static int default_relax_domain_level = -1;
951 int sched_domain_level_max;
952
953 static int __init setup_relax_domain_level(char *str)
954 {
955         if (kstrtoint(str, 0, &default_relax_domain_level))
956                 pr_warn("Unable to set relax_domain_level\n");
957
958         return 1;
959 }
960 __setup("relax_domain_level=", setup_relax_domain_level);
961
962 static void set_domain_attribute(struct sched_domain *sd,
963                                  struct sched_domain_attr *attr)
964 {
965         int request;
966
967         if (!attr || attr->relax_domain_level < 0) {
968                 if (default_relax_domain_level < 0)
969                         return;
970                 else
971                         request = default_relax_domain_level;
972         } else
973                 request = attr->relax_domain_level;
974         if (request < sd->level) {
975                 /* Turn off idle balance on this domain: */
976                 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
977         } else {
978                 /* Turn on idle balance on this domain: */
979                 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
980         }
981 }
982
983 static void __sdt_free(const struct cpumask *cpu_map);
984 static int __sdt_alloc(const struct cpumask *cpu_map);
985
986 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
987                                  const struct cpumask *cpu_map)
988 {
989         switch (what) {
990         case sa_rootdomain:
991                 if (!atomic_read(&d->rd->refcount))
992                         free_rootdomain(&d->rd->rcu);
993                 /* Fall through */
994         case sa_sd:
995                 free_percpu(d->sd);
996                 /* Fall through */
997         case sa_sd_storage:
998                 __sdt_free(cpu_map);
999                 /* Fall through */
1000         case sa_none:
1001                 break;
1002         }
1003 }
1004
1005 static enum s_alloc
1006 __visit_domain_allocation_hell(struct s_data *d, const struct cpumask *cpu_map)
1007 {
1008         memset(d, 0, sizeof(*d));
1009
1010         if (__sdt_alloc(cpu_map))
1011                 return sa_sd_storage;
1012         d->sd = alloc_percpu(struct sched_domain *);
1013         if (!d->sd)
1014                 return sa_sd_storage;
1015         d->rd = alloc_rootdomain();
1016         if (!d->rd)
1017                 return sa_sd;
1018         return sa_rootdomain;
1019 }
1020
1021 /*
1022  * NULL the sd_data elements we've used to build the sched_domain and
1023  * sched_group structure so that the subsequent __free_domain_allocs()
1024  * will not free the data we're using.
1025  */
1026 static void claim_allocations(int cpu, struct sched_domain *sd)
1027 {
1028         struct sd_data *sdd = sd->private;
1029
1030         WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
1031         *per_cpu_ptr(sdd->sd, cpu) = NULL;
1032
1033         if (atomic_read(&(*per_cpu_ptr(sdd->sds, cpu))->ref))
1034                 *per_cpu_ptr(sdd->sds, cpu) = NULL;
1035
1036         if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
1037                 *per_cpu_ptr(sdd->sg, cpu) = NULL;
1038
1039         if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
1040                 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
1041 }
1042
1043 #ifdef CONFIG_NUMA
1044 static int sched_domains_numa_levels;
1045 enum numa_topology_type sched_numa_topology_type;
1046 static int *sched_domains_numa_distance;
1047 int sched_max_numa_distance;
1048 static struct cpumask ***sched_domains_numa_masks;
1049 static int sched_domains_curr_level;
1050 #endif
1051
1052 /*
1053  * SD_flags allowed in topology descriptions.
1054  *
1055  * These flags are purely descriptive of the topology and do not prescribe
1056  * behaviour. Behaviour is artificial and mapped in the below sd_init()
1057  * function:
1058  *
1059  *   SD_SHARE_CPUCAPACITY   - describes SMT topologies
1060  *   SD_SHARE_PKG_RESOURCES - describes shared caches
1061  *   SD_NUMA                - describes NUMA topologies
1062  *   SD_SHARE_POWERDOMAIN   - describes shared power domain
1063  *   SD_ASYM_CPUCAPACITY    - describes mixed capacity topologies
1064  *
1065  * Odd one out, which beside describing the topology has a quirk also
1066  * prescribes the desired behaviour that goes along with it:
1067  *
1068  *   SD_ASYM_PACKING        - describes SMT quirks
1069  */
1070 #define TOPOLOGY_SD_FLAGS               \
1071         (SD_SHARE_CPUCAPACITY |         \
1072          SD_SHARE_PKG_RESOURCES |       \
1073          SD_NUMA |                      \
1074          SD_ASYM_PACKING |              \
1075          SD_ASYM_CPUCAPACITY |          \
1076          SD_SHARE_POWERDOMAIN)
1077
1078 static struct sched_domain *
1079 sd_init(struct sched_domain_topology_level *tl,
1080         const struct cpumask *cpu_map,
1081         struct sched_domain *child, int cpu)
1082 {
1083         struct sd_data *sdd = &tl->data;
1084         struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
1085         int sd_id, sd_weight, sd_flags = 0;
1086
1087 #ifdef CONFIG_NUMA
1088         /*
1089          * Ugly hack to pass state to sd_numa_mask()...
1090          */
1091         sched_domains_curr_level = tl->numa_level;
1092 #endif
1093
1094         sd_weight = cpumask_weight(tl->mask(cpu));
1095
1096         if (tl->sd_flags)
1097                 sd_flags = (*tl->sd_flags)();
1098         if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
1099                         "wrong sd_flags in topology description\n"))
1100                 sd_flags &= ~TOPOLOGY_SD_FLAGS;
1101
1102         *sd = (struct sched_domain){
1103                 .min_interval           = sd_weight,
1104                 .max_interval           = 2*sd_weight,
1105                 .busy_factor            = 32,
1106                 .imbalance_pct          = 125,
1107
1108                 .cache_nice_tries       = 0,
1109                 .busy_idx               = 0,
1110                 .idle_idx               = 0,
1111                 .newidle_idx            = 0,
1112                 .wake_idx               = 0,
1113                 .forkexec_idx           = 0,
1114
1115                 .flags                  = 1*SD_LOAD_BALANCE
1116                                         | 1*SD_BALANCE_NEWIDLE
1117                                         | 1*SD_BALANCE_EXEC
1118                                         | 1*SD_BALANCE_FORK
1119                                         | 0*SD_BALANCE_WAKE
1120                                         | 1*SD_WAKE_AFFINE
1121                                         | 0*SD_SHARE_CPUCAPACITY
1122                                         | 0*SD_SHARE_PKG_RESOURCES
1123                                         | 0*SD_SERIALIZE
1124                                         | 0*SD_PREFER_SIBLING
1125                                         | 0*SD_NUMA
1126                                         | sd_flags
1127                                         ,
1128
1129                 .last_balance           = jiffies,
1130                 .balance_interval       = sd_weight,
1131                 .smt_gain               = 0,
1132                 .max_newidle_lb_cost    = 0,
1133                 .next_decay_max_lb_cost = jiffies,
1134                 .child                  = child,
1135 #ifdef CONFIG_SCHED_DEBUG
1136                 .name                   = tl->name,
1137 #endif
1138         };
1139
1140         cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
1141         sd_id = cpumask_first(sched_domain_span(sd));
1142
1143         /*
1144          * Convert topological properties into behaviour.
1145          */
1146
1147         if (sd->flags & SD_ASYM_CPUCAPACITY) {
1148                 struct sched_domain *t = sd;
1149
1150                 for_each_lower_domain(t)
1151                         t->flags |= SD_BALANCE_WAKE;
1152         }
1153
1154         if (sd->flags & SD_SHARE_CPUCAPACITY) {
1155                 sd->flags |= SD_PREFER_SIBLING;
1156                 sd->imbalance_pct = 110;
1157                 sd->smt_gain = 1178; /* ~15% */
1158
1159         } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
1160                 sd->imbalance_pct = 117;
1161                 sd->cache_nice_tries = 1;
1162                 sd->busy_idx = 2;
1163
1164 #ifdef CONFIG_NUMA
1165         } else if (sd->flags & SD_NUMA) {
1166                 sd->cache_nice_tries = 2;
1167                 sd->busy_idx = 3;
1168                 sd->idle_idx = 2;
1169
1170                 sd->flags |= SD_SERIALIZE;
1171                 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
1172                         sd->flags &= ~(SD_BALANCE_EXEC |
1173                                        SD_BALANCE_FORK |
1174                                        SD_WAKE_AFFINE);
1175                 }
1176
1177 #endif
1178         } else {
1179                 sd->flags |= SD_PREFER_SIBLING;
1180                 sd->cache_nice_tries = 1;
1181                 sd->busy_idx = 2;
1182                 sd->idle_idx = 1;
1183         }
1184
1185         /*
1186          * For all levels sharing cache; connect a sched_domain_shared
1187          * instance.
1188          */
1189         if (sd->flags & SD_SHARE_PKG_RESOURCES) {
1190                 sd->shared = *per_cpu_ptr(sdd->sds, sd_id);
1191                 atomic_inc(&sd->shared->ref);
1192                 atomic_set(&sd->shared->nr_busy_cpus, sd_weight);
1193         }
1194
1195         sd->private = sdd;
1196
1197         return sd;
1198 }
1199
1200 /*
1201  * Topology list, bottom-up.
1202  */
1203 static struct sched_domain_topology_level default_topology[] = {
1204 #ifdef CONFIG_SCHED_SMT
1205         { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
1206 #endif
1207 #ifdef CONFIG_SCHED_MC
1208         { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
1209 #endif
1210         { cpu_cpu_mask, SD_INIT_NAME(DIE) },
1211         { NULL, },
1212 };
1213
1214 static struct sched_domain_topology_level *sched_domain_topology =
1215         default_topology;
1216
1217 #define for_each_sd_topology(tl)                        \
1218         for (tl = sched_domain_topology; tl->mask; tl++)
1219
1220 void set_sched_topology(struct sched_domain_topology_level *tl)
1221 {
1222         if (WARN_ON_ONCE(sched_smp_initialized))
1223                 return;
1224
1225         sched_domain_topology = tl;
1226 }
1227
1228 #ifdef CONFIG_NUMA
1229
1230 static const struct cpumask *sd_numa_mask(int cpu)
1231 {
1232         return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
1233 }
1234
1235 static void sched_numa_warn(const char *str)
1236 {
1237         static int done = false;
1238         int i,j;
1239
1240         if (done)
1241                 return;
1242
1243         done = true;
1244
1245         printk(KERN_WARNING "ERROR: %s\n\n", str);
1246
1247         for (i = 0; i < nr_node_ids; i++) {
1248                 printk(KERN_WARNING "  ");
1249                 for (j = 0; j < nr_node_ids; j++)
1250                         printk(KERN_CONT "%02d ", node_distance(i,j));
1251                 printk(KERN_CONT "\n");
1252         }
1253         printk(KERN_WARNING "\n");
1254 }
1255
1256 bool find_numa_distance(int distance)
1257 {
1258         int i;
1259
1260         if (distance == node_distance(0, 0))
1261                 return true;
1262
1263         for (i = 0; i < sched_domains_numa_levels; i++) {
1264                 if (sched_domains_numa_distance[i] == distance)
1265                         return true;
1266         }
1267
1268         return false;
1269 }
1270
1271 /*
1272  * A system can have three types of NUMA topology:
1273  * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
1274  * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
1275  * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
1276  *
1277  * The difference between a glueless mesh topology and a backplane
1278  * topology lies in whether communication between not directly
1279  * connected nodes goes through intermediary nodes (where programs
1280  * could run), or through backplane controllers. This affects
1281  * placement of programs.
1282  *
1283  * The type of topology can be discerned with the following tests:
1284  * - If the maximum distance between any nodes is 1 hop, the system
1285  *   is directly connected.
1286  * - If for two nodes A and B, located N > 1 hops away from each other,
1287  *   there is an intermediary node C, which is < N hops away from both
1288  *   nodes A and B, the system is a glueless mesh.
1289  */
1290 static void init_numa_topology_type(void)
1291 {
1292         int a, b, c, n;
1293
1294         n = sched_max_numa_distance;
1295
1296         if (sched_domains_numa_levels <= 1) {
1297                 sched_numa_topology_type = NUMA_DIRECT;
1298                 return;
1299         }
1300
1301         for_each_online_node(a) {
1302                 for_each_online_node(b) {
1303                         /* Find two nodes furthest removed from each other. */
1304                         if (node_distance(a, b) < n)
1305                                 continue;
1306
1307                         /* Is there an intermediary node between a and b? */
1308                         for_each_online_node(c) {
1309                                 if (node_distance(a, c) < n &&
1310                                     node_distance(b, c) < n) {
1311                                         sched_numa_topology_type =
1312                                                         NUMA_GLUELESS_MESH;
1313                                         return;
1314                                 }
1315                         }
1316
1317                         sched_numa_topology_type = NUMA_BACKPLANE;
1318                         return;
1319                 }
1320         }
1321 }
1322
1323 void sched_init_numa(void)
1324 {
1325         int next_distance, curr_distance = node_distance(0, 0);
1326         struct sched_domain_topology_level *tl;
1327         int level = 0;
1328         int i, j, k;
1329
1330         sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
1331         if (!sched_domains_numa_distance)
1332                 return;
1333
1334         /*
1335          * O(nr_nodes^2) deduplicating selection sort -- in order to find the
1336          * unique distances in the node_distance() table.
1337          *
1338          * Assumes node_distance(0,j) includes all distances in
1339          * node_distance(i,j) in order to avoid cubic time.
1340          */
1341         next_distance = curr_distance;
1342         for (i = 0; i < nr_node_ids; i++) {
1343                 for (j = 0; j < nr_node_ids; j++) {
1344                         for (k = 0; k < nr_node_ids; k++) {
1345                                 int distance = node_distance(i, k);
1346
1347                                 if (distance > curr_distance &&
1348                                     (distance < next_distance ||
1349                                      next_distance == curr_distance))
1350                                         next_distance = distance;
1351
1352                                 /*
1353                                  * While not a strong assumption it would be nice to know
1354                                  * about cases where if node A is connected to B, B is not
1355                                  * equally connected to A.
1356                                  */
1357                                 if (sched_debug() && node_distance(k, i) != distance)
1358                                         sched_numa_warn("Node-distance not symmetric");
1359
1360                                 if (sched_debug() && i && !find_numa_distance(distance))
1361                                         sched_numa_warn("Node-0 not representative");
1362                         }
1363                         if (next_distance != curr_distance) {
1364                                 sched_domains_numa_distance[level++] = next_distance;
1365                                 sched_domains_numa_levels = level;
1366                                 curr_distance = next_distance;
1367                         } else break;
1368                 }
1369
1370                 /*
1371                  * In case of sched_debug() we verify the above assumption.
1372                  */
1373                 if (!sched_debug())
1374                         break;
1375         }
1376
1377         if (!level)
1378                 return;
1379
1380         /*
1381          * 'level' contains the number of unique distances, excluding the
1382          * identity distance node_distance(i,i).
1383          *
1384          * The sched_domains_numa_distance[] array includes the actual distance
1385          * numbers.
1386          */
1387
1388         /*
1389          * Here, we should temporarily reset sched_domains_numa_levels to 0.
1390          * If it fails to allocate memory for array sched_domains_numa_masks[][],
1391          * the array will contain less then 'level' members. This could be
1392          * dangerous when we use it to iterate array sched_domains_numa_masks[][]
1393          * in other functions.
1394          *
1395          * We reset it to 'level' at the end of this function.
1396          */
1397         sched_domains_numa_levels = 0;
1398
1399         sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
1400         if (!sched_domains_numa_masks)
1401                 return;
1402
1403         /*
1404          * Now for each level, construct a mask per node which contains all
1405          * CPUs of nodes that are that many hops away from us.
1406          */
1407         for (i = 0; i < level; i++) {
1408                 sched_domains_numa_masks[i] =
1409                         kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
1410                 if (!sched_domains_numa_masks[i])
1411                         return;
1412
1413                 for (j = 0; j < nr_node_ids; j++) {
1414                         struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
1415                         if (!mask)
1416                                 return;
1417
1418                         sched_domains_numa_masks[i][j] = mask;
1419
1420                         for_each_node(k) {
1421                                 if (node_distance(j, k) > sched_domains_numa_distance[i])
1422                                         continue;
1423
1424                                 cpumask_or(mask, mask, cpumask_of_node(k));
1425                         }
1426                 }
1427         }
1428
1429         /* Compute default topology size */
1430         for (i = 0; sched_domain_topology[i].mask; i++);
1431
1432         tl = kzalloc((i + level + 1) *
1433                         sizeof(struct sched_domain_topology_level), GFP_KERNEL);
1434         if (!tl)
1435                 return;
1436
1437         /*
1438          * Copy the default topology bits..
1439          */
1440         for (i = 0; sched_domain_topology[i].mask; i++)
1441                 tl[i] = sched_domain_topology[i];
1442
1443         /*
1444          * .. and append 'j' levels of NUMA goodness.
1445          */
1446         for (j = 0; j < level; i++, j++) {
1447                 tl[i] = (struct sched_domain_topology_level){
1448                         .mask = sd_numa_mask,
1449                         .sd_flags = cpu_numa_flags,
1450                         .flags = SDTL_OVERLAP,
1451                         .numa_level = j,
1452                         SD_INIT_NAME(NUMA)
1453                 };
1454         }
1455
1456         sched_domain_topology = tl;
1457
1458         sched_domains_numa_levels = level;
1459         sched_max_numa_distance = sched_domains_numa_distance[level - 1];
1460
1461         init_numa_topology_type();
1462 }
1463
1464 void sched_domains_numa_masks_set(unsigned int cpu)
1465 {
1466         int node = cpu_to_node(cpu);
1467         int i, j;
1468
1469         for (i = 0; i < sched_domains_numa_levels; i++) {
1470                 for (j = 0; j < nr_node_ids; j++) {
1471                         if (node_distance(j, node) <= sched_domains_numa_distance[i])
1472                                 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
1473                 }
1474         }
1475 }
1476
1477 void sched_domains_numa_masks_clear(unsigned int cpu)
1478 {
1479         int i, j;
1480
1481         for (i = 0; i < sched_domains_numa_levels; i++) {
1482                 for (j = 0; j < nr_node_ids; j++)
1483                         cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
1484         }
1485 }
1486
1487 #endif /* CONFIG_NUMA */
1488
1489 static int __sdt_alloc(const struct cpumask *cpu_map)
1490 {
1491         struct sched_domain_topology_level *tl;
1492         int j;
1493
1494         for_each_sd_topology(tl) {
1495                 struct sd_data *sdd = &tl->data;
1496
1497                 sdd->sd = alloc_percpu(struct sched_domain *);
1498                 if (!sdd->sd)
1499                         return -ENOMEM;
1500
1501                 sdd->sds = alloc_percpu(struct sched_domain_shared *);
1502                 if (!sdd->sds)
1503                         return -ENOMEM;
1504
1505                 sdd->sg = alloc_percpu(struct sched_group *);
1506                 if (!sdd->sg)
1507                         return -ENOMEM;
1508
1509                 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
1510                 if (!sdd->sgc)
1511                         return -ENOMEM;
1512
1513                 for_each_cpu(j, cpu_map) {
1514                         struct sched_domain *sd;
1515                         struct sched_domain_shared *sds;
1516                         struct sched_group *sg;
1517                         struct sched_group_capacity *sgc;
1518
1519                         sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
1520                                         GFP_KERNEL, cpu_to_node(j));
1521                         if (!sd)
1522                                 return -ENOMEM;
1523
1524                         *per_cpu_ptr(sdd->sd, j) = sd;
1525
1526                         sds = kzalloc_node(sizeof(struct sched_domain_shared),
1527                                         GFP_KERNEL, cpu_to_node(j));
1528                         if (!sds)
1529                                 return -ENOMEM;
1530
1531                         *per_cpu_ptr(sdd->sds, j) = sds;
1532
1533                         sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
1534                                         GFP_KERNEL, cpu_to_node(j));
1535                         if (!sg)
1536                                 return -ENOMEM;
1537
1538                         sg->next = sg;
1539
1540                         *per_cpu_ptr(sdd->sg, j) = sg;
1541
1542                         sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
1543                                         GFP_KERNEL, cpu_to_node(j));
1544                         if (!sgc)
1545                                 return -ENOMEM;
1546
1547 #ifdef CONFIG_SCHED_DEBUG
1548                         sgc->id = j;
1549 #endif
1550
1551                         *per_cpu_ptr(sdd->sgc, j) = sgc;
1552                 }
1553         }
1554
1555         return 0;
1556 }
1557
1558 static void __sdt_free(const struct cpumask *cpu_map)
1559 {
1560         struct sched_domain_topology_level *tl;
1561         int j;
1562
1563         for_each_sd_topology(tl) {
1564                 struct sd_data *sdd = &tl->data;
1565
1566                 for_each_cpu(j, cpu_map) {
1567                         struct sched_domain *sd;
1568
1569                         if (sdd->sd) {
1570                                 sd = *per_cpu_ptr(sdd->sd, j);
1571                                 if (sd && (sd->flags & SD_OVERLAP))
1572                                         free_sched_groups(sd->groups, 0);
1573                                 kfree(*per_cpu_ptr(sdd->sd, j));
1574                         }
1575
1576                         if (sdd->sds)
1577                                 kfree(*per_cpu_ptr(sdd->sds, j));
1578                         if (sdd->sg)
1579                                 kfree(*per_cpu_ptr(sdd->sg, j));
1580                         if (sdd->sgc)
1581                                 kfree(*per_cpu_ptr(sdd->sgc, j));
1582                 }
1583                 free_percpu(sdd->sd);
1584                 sdd->sd = NULL;
1585                 free_percpu(sdd->sds);
1586                 sdd->sds = NULL;
1587                 free_percpu(sdd->sg);
1588                 sdd->sg = NULL;
1589                 free_percpu(sdd->sgc);
1590                 sdd->sgc = NULL;
1591         }
1592 }
1593
1594 static struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
1595                 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
1596                 struct sched_domain *child, int cpu)
1597 {
1598         struct sched_domain *sd = sd_init(tl, cpu_map, child, cpu);
1599
1600         if (child) {
1601                 sd->level = child->level + 1;
1602                 sched_domain_level_max = max(sched_domain_level_max, sd->level);
1603                 child->parent = sd;
1604
1605                 if (!cpumask_subset(sched_domain_span(child),
1606                                     sched_domain_span(sd))) {
1607                         pr_err("BUG: arch topology borken\n");
1608 #ifdef CONFIG_SCHED_DEBUG
1609                         pr_err("     the %s domain not a subset of the %s domain\n",
1610                                         child->name, sd->name);
1611 #endif
1612                         /* Fixup, ensure @sd has at least @child cpus. */
1613                         cpumask_or(sched_domain_span(sd),
1614                                    sched_domain_span(sd),
1615                                    sched_domain_span(child));
1616                 }
1617
1618         }
1619         set_domain_attribute(sd, attr);
1620
1621         return sd;
1622 }
1623
1624 /*
1625  * Build sched domains for a given set of CPUs and attach the sched domains
1626  * to the individual CPUs
1627  */
1628 static int
1629 build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr)
1630 {
1631         enum s_alloc alloc_state;
1632         struct sched_domain *sd;
1633         struct s_data d;
1634         struct rq *rq = NULL;
1635         int i, ret = -ENOMEM;
1636
1637         alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
1638         if (alloc_state != sa_rootdomain)
1639                 goto error;
1640
1641         /* Set up domains for CPUs specified by the cpu_map: */
1642         for_each_cpu(i, cpu_map) {
1643                 struct sched_domain_topology_level *tl;
1644
1645                 sd = NULL;
1646                 for_each_sd_topology(tl) {
1647                         sd = build_sched_domain(tl, cpu_map, attr, sd, i);
1648                         if (tl == sched_domain_topology)
1649                                 *per_cpu_ptr(d.sd, i) = sd;
1650                         if (tl->flags & SDTL_OVERLAP)
1651                                 sd->flags |= SD_OVERLAP;
1652                         if (cpumask_equal(cpu_map, sched_domain_span(sd)))
1653                                 break;
1654                 }
1655         }
1656
1657         /* Build the groups for the domains */
1658         for_each_cpu(i, cpu_map) {
1659                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
1660                         sd->span_weight = cpumask_weight(sched_domain_span(sd));
1661                         if (sd->flags & SD_OVERLAP) {
1662                                 if (build_overlap_sched_groups(sd, i))
1663                                         goto error;
1664                         } else {
1665                                 if (build_sched_groups(sd, i))
1666                                         goto error;
1667                         }
1668                 }
1669         }
1670
1671         /* Calculate CPU capacity for physical packages and nodes */
1672         for (i = nr_cpumask_bits-1; i >= 0; i--) {
1673                 if (!cpumask_test_cpu(i, cpu_map))
1674                         continue;
1675
1676                 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
1677                         claim_allocations(i, sd);
1678                         init_sched_groups_capacity(i, sd);
1679                 }
1680         }
1681
1682         /* Attach the domains */
1683         rcu_read_lock();
1684         for_each_cpu(i, cpu_map) {
1685                 rq = cpu_rq(i);
1686                 sd = *per_cpu_ptr(d.sd, i);
1687
1688                 /* Use READ_ONCE()/WRITE_ONCE() to avoid load/store tearing: */
1689                 if (rq->cpu_capacity_orig > READ_ONCE(d.rd->max_cpu_capacity))
1690                         WRITE_ONCE(d.rd->max_cpu_capacity, rq->cpu_capacity_orig);
1691
1692                 cpu_attach_domain(sd, d.rd, i);
1693         }
1694         rcu_read_unlock();
1695
1696         if (rq && sched_debug_enabled) {
1697                 pr_info("span: %*pbl (max cpu_capacity = %lu)\n",
1698                         cpumask_pr_args(cpu_map), rq->rd->max_cpu_capacity);
1699         }
1700
1701         ret = 0;
1702 error:
1703         __free_domain_allocs(&d, alloc_state, cpu_map);
1704         return ret;
1705 }
1706
1707 /* Current sched domains: */
1708 static cpumask_var_t                    *doms_cur;
1709
1710 /* Number of sched domains in 'doms_cur': */
1711 static int                              ndoms_cur;
1712
1713 /* Attribues of custom domains in 'doms_cur' */
1714 static struct sched_domain_attr         *dattr_cur;
1715
1716 /*
1717  * Special case: If a kmalloc() of a doms_cur partition (array of
1718  * cpumask) fails, then fallback to a single sched domain,
1719  * as determined by the single cpumask fallback_doms.
1720  */
1721 static cpumask_var_t                    fallback_doms;
1722
1723 /*
1724  * arch_update_cpu_topology lets virtualized architectures update the
1725  * CPU core maps. It is supposed to return 1 if the topology changed
1726  * or 0 if it stayed the same.
1727  */
1728 int __weak arch_update_cpu_topology(void)
1729 {
1730         return 0;
1731 }
1732
1733 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
1734 {
1735         int i;
1736         cpumask_var_t *doms;
1737
1738         doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
1739         if (!doms)
1740                 return NULL;
1741         for (i = 0; i < ndoms; i++) {
1742                 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
1743                         free_sched_domains(doms, i);
1744                         return NULL;
1745                 }
1746         }
1747         return doms;
1748 }
1749
1750 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
1751 {
1752         unsigned int i;
1753         for (i = 0; i < ndoms; i++)
1754                 free_cpumask_var(doms[i]);
1755         kfree(doms);
1756 }
1757
1758 /*
1759  * Set up scheduler domains and groups. Callers must hold the hotplug lock.
1760  * For now this just excludes isolated CPUs, but could be used to
1761  * exclude other special cases in the future.
1762  */
1763 int sched_init_domains(const struct cpumask *cpu_map)
1764 {
1765         int err;
1766
1767         zalloc_cpumask_var(&sched_domains_tmpmask, GFP_KERNEL);
1768         zalloc_cpumask_var(&sched_domains_tmpmask2, GFP_KERNEL);
1769         zalloc_cpumask_var(&fallback_doms, GFP_KERNEL);
1770
1771         arch_update_cpu_topology();
1772         ndoms_cur = 1;
1773         doms_cur = alloc_sched_domains(ndoms_cur);
1774         if (!doms_cur)
1775                 doms_cur = &fallback_doms;
1776         cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
1777         err = build_sched_domains(doms_cur[0], NULL);
1778         register_sched_domain_sysctl();
1779
1780         return err;
1781 }
1782
1783 /*
1784  * Detach sched domains from a group of CPUs specified in cpu_map
1785  * These CPUs will now be attached to the NULL domain
1786  */
1787 static void detach_destroy_domains(const struct cpumask *cpu_map)
1788 {
1789         int i;
1790
1791         rcu_read_lock();
1792         for_each_cpu(i, cpu_map)
1793                 cpu_attach_domain(NULL, &def_root_domain, i);
1794         rcu_read_unlock();
1795 }
1796
1797 /* handle null as "default" */
1798 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
1799                         struct sched_domain_attr *new, int idx_new)
1800 {
1801         struct sched_domain_attr tmp;
1802
1803         /* Fast path: */
1804         if (!new && !cur)
1805                 return 1;
1806
1807         tmp = SD_ATTR_INIT;
1808         return !memcmp(cur ? (cur + idx_cur) : &tmp,
1809                         new ? (new + idx_new) : &tmp,
1810                         sizeof(struct sched_domain_attr));
1811 }
1812
1813 /*
1814  * Partition sched domains as specified by the 'ndoms_new'
1815  * cpumasks in the array doms_new[] of cpumasks. This compares
1816  * doms_new[] to the current sched domain partitioning, doms_cur[].
1817  * It destroys each deleted domain and builds each new domain.
1818  *
1819  * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
1820  * The masks don't intersect (don't overlap.) We should setup one
1821  * sched domain for each mask. CPUs not in any of the cpumasks will
1822  * not be load balanced. If the same cpumask appears both in the
1823  * current 'doms_cur' domains and in the new 'doms_new', we can leave
1824  * it as it is.
1825  *
1826  * The passed in 'doms_new' should be allocated using
1827  * alloc_sched_domains.  This routine takes ownership of it and will
1828  * free_sched_domains it when done with it. If the caller failed the
1829  * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
1830  * and partition_sched_domains() will fallback to the single partition
1831  * 'fallback_doms', it also forces the domains to be rebuilt.
1832  *
1833  * If doms_new == NULL it will be replaced with cpu_online_mask.
1834  * ndoms_new == 0 is a special case for destroying existing domains,
1835  * and it will not create the default domain.
1836  *
1837  * Call with hotplug lock held
1838  */
1839 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
1840                              struct sched_domain_attr *dattr_new)
1841 {
1842         int i, j, n;
1843         int new_topology;
1844
1845         mutex_lock(&sched_domains_mutex);
1846
1847         /* Always unregister in case we don't destroy any domains: */
1848         unregister_sched_domain_sysctl();
1849
1850         /* Let the architecture update CPU core mappings: */
1851         new_topology = arch_update_cpu_topology();
1852
1853         if (!doms_new) {
1854                 WARN_ON_ONCE(dattr_new);
1855                 n = 0;
1856                 doms_new = alloc_sched_domains(1);
1857                 if (doms_new) {
1858                         n = 1;
1859                         cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
1860                 }
1861         } else {
1862                 n = ndoms_new;
1863         }
1864
1865         /* Destroy deleted domains: */
1866         for (i = 0; i < ndoms_cur; i++) {
1867                 for (j = 0; j < n && !new_topology; j++) {
1868                         if (cpumask_equal(doms_cur[i], doms_new[j])
1869                             && dattrs_equal(dattr_cur, i, dattr_new, j))
1870                                 goto match1;
1871                 }
1872                 /* No match - a current sched domain not in new doms_new[] */
1873                 detach_destroy_domains(doms_cur[i]);
1874 match1:
1875                 ;
1876         }
1877
1878         n = ndoms_cur;
1879         if (!doms_new) {
1880                 n = 0;
1881                 doms_new = &fallback_doms;
1882                 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
1883         }
1884
1885         /* Build new domains: */
1886         for (i = 0; i < ndoms_new; i++) {
1887                 for (j = 0; j < n && !new_topology; j++) {
1888                         if (cpumask_equal(doms_new[i], doms_cur[j])
1889                             && dattrs_equal(dattr_new, i, dattr_cur, j))
1890                                 goto match2;
1891                 }
1892                 /* No match - add a new doms_new */
1893                 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
1894 match2:
1895                 ;
1896         }
1897
1898         /* Remember the new sched domains: */
1899         if (doms_cur != &fallback_doms)
1900                 free_sched_domains(doms_cur, ndoms_cur);
1901
1902         kfree(dattr_cur);
1903         doms_cur = doms_new;
1904         dattr_cur = dattr_new;
1905         ndoms_cur = ndoms_new;
1906
1907         register_sched_domain_sysctl();
1908
1909         mutex_unlock(&sched_domains_mutex);
1910 }
1911