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