xref: /linux/kernel/sched/topology.c (revision cd959a3562050d1c676be37f1d256a96cb067868)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Scheduler topology setup/handling methods
4  */
5 
6 #include <linux/sched/isolation.h>
7 #include <linux/bsearch.h>
8 #include "sched.h"
9 
10 DEFINE_MUTEX(sched_domains_mutex);
11 void sched_domains_mutex_lock(void)
12 {
13 	mutex_lock(&sched_domains_mutex);
14 }
15 void sched_domains_mutex_unlock(void)
16 {
17 	mutex_unlock(&sched_domains_mutex);
18 }
19 
20 /* Protected by sched_domains_mutex: */
21 static cpumask_var_t sched_domains_tmpmask;
22 static cpumask_var_t sched_domains_tmpmask2;
23 
24 static int __init sched_debug_setup(char *str)
25 {
26 	sched_debug_verbose = true;
27 
28 	return 0;
29 }
30 early_param("sched_verbose", sched_debug_setup);
31 
32 static inline bool sched_debug(void)
33 {
34 	return sched_debug_verbose;
35 }
36 
37 #define SD_FLAG(_name, mflags) [__##_name] = { .meta_flags = mflags, .name = #_name },
38 const struct sd_flag_debug sd_flag_debug[] = {
39 #include <linux/sched/sd_flags.h>
40 };
41 #undef SD_FLAG
42 
43 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
44 				  struct cpumask *groupmask)
45 {
46 	struct sched_group *group = sd->groups;
47 	unsigned long flags = sd->flags;
48 	unsigned int idx;
49 
50 	cpumask_clear(groupmask);
51 
52 	printk(KERN_DEBUG "%*s domain-%d: ", level, "", level);
53 	printk(KERN_CONT "span=%*pbl level=%s\n",
54 	       cpumask_pr_args(sched_domain_span(sd)), sd->name);
55 
56 	if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
57 		printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
58 	}
59 	if (group && !cpumask_test_cpu(cpu, sched_group_span(group))) {
60 		printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
61 	}
62 
63 	for_each_set_bit(idx, &flags, __SD_FLAG_CNT) {
64 		unsigned int flag = BIT(idx);
65 		unsigned int meta_flags = sd_flag_debug[idx].meta_flags;
66 
67 		if ((meta_flags & SDF_SHARED_CHILD) && sd->child &&
68 		    !(sd->child->flags & flag))
69 			printk(KERN_ERR "ERROR: flag %s set here but not in child\n",
70 			       sd_flag_debug[idx].name);
71 
72 		if ((meta_flags & SDF_SHARED_PARENT) && sd->parent &&
73 		    !(sd->parent->flags & flag))
74 			printk(KERN_ERR "ERROR: flag %s set here but not in parent\n",
75 			       sd_flag_debug[idx].name);
76 	}
77 
78 	printk(KERN_DEBUG "%*s groups:", level + 1, "");
79 	do {
80 		if (!group) {
81 			printk("\n");
82 			printk(KERN_ERR "ERROR: group is NULL\n");
83 			break;
84 		}
85 
86 		if (cpumask_empty(sched_group_span(group))) {
87 			printk(KERN_CONT "\n");
88 			printk(KERN_ERR "ERROR: empty group\n");
89 			break;
90 		}
91 
92 		if (!(sd->flags & SD_NUMA) &&
93 		    cpumask_intersects(groupmask, sched_group_span(group))) {
94 			printk(KERN_CONT "\n");
95 			printk(KERN_ERR "ERROR: repeated CPUs\n");
96 			break;
97 		}
98 
99 		cpumask_or(groupmask, groupmask, sched_group_span(group));
100 
101 		printk(KERN_CONT " %d:{ span=%*pbl",
102 				group->sgc->id,
103 				cpumask_pr_args(sched_group_span(group)));
104 
105 		if ((sd->flags & SD_NUMA) &&
106 		    !cpumask_equal(group_balance_mask(group), sched_group_span(group))) {
107 			printk(KERN_CONT " mask=%*pbl",
108 				cpumask_pr_args(group_balance_mask(group)));
109 		}
110 
111 		if (group->sgc->capacity != SCHED_CAPACITY_SCALE)
112 			printk(KERN_CONT " cap=%lu", group->sgc->capacity);
113 
114 		if (group == sd->groups && sd->child &&
115 		    !cpumask_equal(sched_domain_span(sd->child),
116 				   sched_group_span(group))) {
117 			printk(KERN_ERR "ERROR: domain->groups does not match domain->child\n");
118 		}
119 
120 		printk(KERN_CONT " }");
121 
122 		group = group->next;
123 
124 		if (group != sd->groups)
125 			printk(KERN_CONT ",");
126 
127 	} while (group != sd->groups);
128 	printk(KERN_CONT "\n");
129 
130 	if (!cpumask_equal(sched_domain_span(sd), groupmask))
131 		printk(KERN_ERR "ERROR: groups don't span domain->span\n");
132 
133 	if (sd->parent &&
134 	    !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
135 		printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
136 	return 0;
137 }
138 
139 static void sched_domain_debug(struct sched_domain *sd, int cpu)
140 {
141 	int level = 0;
142 
143 	if (!sched_debug_verbose)
144 		return;
145 
146 	if (!sd) {
147 		printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
148 		return;
149 	}
150 
151 	printk(KERN_DEBUG "CPU%d attaching sched-domain(s):\n", cpu);
152 
153 	for (;;) {
154 		if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
155 			break;
156 		level++;
157 		sd = sd->parent;
158 		if (!sd)
159 			break;
160 	}
161 }
162 
163 /* Generate a mask of SD flags with the SDF_NEEDS_GROUPS metaflag */
164 #define SD_FLAG(name, mflags) (name * !!((mflags) & SDF_NEEDS_GROUPS)) |
165 static const unsigned int SD_DEGENERATE_GROUPS_MASK =
166 #include <linux/sched/sd_flags.h>
167 0;
168 #undef SD_FLAG
169 
170 static int sd_degenerate(struct sched_domain *sd)
171 {
172 	if (cpumask_weight(sched_domain_span(sd)) == 1)
173 		return 1;
174 
175 	/* Following flags need at least 2 groups */
176 	if ((sd->flags & SD_DEGENERATE_GROUPS_MASK) &&
177 	    (sd->groups != sd->groups->next))
178 		return 0;
179 
180 	/* Following flags don't use groups */
181 	if (sd->flags & (SD_WAKE_AFFINE))
182 		return 0;
183 
184 	return 1;
185 }
186 
187 static int
188 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
189 {
190 	unsigned long cflags = sd->flags, pflags = parent->flags;
191 
192 	if (sd_degenerate(parent))
193 		return 1;
194 
195 	if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
196 		return 0;
197 
198 	/* Flags needing groups don't count if only 1 group in parent */
199 	if (parent->groups == parent->groups->next)
200 		pflags &= ~SD_DEGENERATE_GROUPS_MASK;
201 
202 	if (~cflags & pflags)
203 		return 0;
204 
205 	return 1;
206 }
207 
208 #if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL)
209 DEFINE_STATIC_KEY_FALSE(sched_energy_present);
210 static unsigned int sysctl_sched_energy_aware = 1;
211 static DEFINE_MUTEX(sched_energy_mutex);
212 static bool sched_energy_update;
213 
214 static bool sched_is_eas_possible(const struct cpumask *cpu_mask)
215 {
216 	bool any_asym_capacity = false;
217 	int i;
218 
219 	/* EAS is enabled for asymmetric CPU capacity topologies. */
220 	for_each_cpu(i, cpu_mask) {
221 		if (rcu_access_pointer(per_cpu(sd_asym_cpucapacity, i))) {
222 			any_asym_capacity = true;
223 			break;
224 		}
225 	}
226 	if (!any_asym_capacity) {
227 		if (sched_debug()) {
228 			pr_info("rd %*pbl: Checking EAS, CPUs do not have asymmetric capacities\n",
229 				cpumask_pr_args(cpu_mask));
230 		}
231 		return false;
232 	}
233 
234 	/* EAS definitely does *not* handle SMT */
235 	if (sched_smt_active()) {
236 		if (sched_debug()) {
237 			pr_info("rd %*pbl: Checking EAS, SMT is not supported\n",
238 				cpumask_pr_args(cpu_mask));
239 		}
240 		return false;
241 	}
242 
243 	if (!arch_scale_freq_invariant()) {
244 		if (sched_debug()) {
245 			pr_info("rd %*pbl: Checking EAS: frequency-invariant load tracking not yet supported",
246 				cpumask_pr_args(cpu_mask));
247 		}
248 		return false;
249 	}
250 
251 	if (!cpufreq_ready_for_eas(cpu_mask)) {
252 		if (sched_debug()) {
253 			pr_info("rd %*pbl: Checking EAS: cpufreq is not ready\n",
254 				cpumask_pr_args(cpu_mask));
255 		}
256 		return false;
257 	}
258 
259 	return true;
260 }
261 
262 void rebuild_sched_domains_energy(void)
263 {
264 	mutex_lock(&sched_energy_mutex);
265 	sched_energy_update = true;
266 	rebuild_sched_domains();
267 	sched_energy_update = false;
268 	mutex_unlock(&sched_energy_mutex);
269 }
270 
271 #ifdef CONFIG_PROC_SYSCTL
272 static int sched_energy_aware_handler(const struct ctl_table *table, int write,
273 		void *buffer, size_t *lenp, loff_t *ppos)
274 {
275 	int ret, state;
276 
277 	if (write && !capable(CAP_SYS_ADMIN))
278 		return -EPERM;
279 
280 	if (!sched_is_eas_possible(cpu_active_mask)) {
281 		if (write) {
282 			return -EOPNOTSUPP;
283 		} else {
284 			*lenp = 0;
285 			return 0;
286 		}
287 	}
288 
289 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
290 	if (!ret && write) {
291 		state = static_branch_unlikely(&sched_energy_present);
292 		if (state != sysctl_sched_energy_aware)
293 			rebuild_sched_domains_energy();
294 	}
295 
296 	return ret;
297 }
298 
299 static const struct ctl_table sched_energy_aware_sysctls[] = {
300 	{
301 		.procname       = "sched_energy_aware",
302 		.data           = &sysctl_sched_energy_aware,
303 		.maxlen         = sizeof(unsigned int),
304 		.mode           = 0644,
305 		.proc_handler   = sched_energy_aware_handler,
306 		.extra1         = SYSCTL_ZERO,
307 		.extra2         = SYSCTL_ONE,
308 	},
309 };
310 
311 static int __init sched_energy_aware_sysctl_init(void)
312 {
313 	register_sysctl_init("kernel", sched_energy_aware_sysctls);
314 	return 0;
315 }
316 
317 late_initcall(sched_energy_aware_sysctl_init);
318 #endif /* CONFIG_PROC_SYSCTL */
319 
320 static void free_pd(struct perf_domain *pd)
321 {
322 	struct perf_domain *tmp;
323 
324 	while (pd) {
325 		tmp = pd->next;
326 		kfree(pd);
327 		pd = tmp;
328 	}
329 }
330 
331 static struct perf_domain *find_pd(struct perf_domain *pd, int cpu)
332 {
333 	while (pd) {
334 		if (cpumask_test_cpu(cpu, perf_domain_span(pd)))
335 			return pd;
336 		pd = pd->next;
337 	}
338 
339 	return NULL;
340 }
341 
342 static struct perf_domain *pd_init(int cpu)
343 {
344 	struct em_perf_domain *obj = em_cpu_get(cpu);
345 	struct perf_domain *pd;
346 
347 	if (!obj) {
348 		if (sched_debug())
349 			pr_info("%s: no EM found for CPU%d\n", __func__, cpu);
350 		return NULL;
351 	}
352 
353 	pd = kzalloc(sizeof(*pd), GFP_KERNEL);
354 	if (!pd)
355 		return NULL;
356 	pd->em_pd = obj;
357 
358 	return pd;
359 }
360 
361 static void perf_domain_debug(const struct cpumask *cpu_map,
362 						struct perf_domain *pd)
363 {
364 	if (!sched_debug() || !pd)
365 		return;
366 
367 	printk(KERN_DEBUG "root_domain %*pbl:", cpumask_pr_args(cpu_map));
368 
369 	while (pd) {
370 		printk(KERN_CONT " pd%d:{ cpus=%*pbl nr_pstate=%d }",
371 				cpumask_first(perf_domain_span(pd)),
372 				cpumask_pr_args(perf_domain_span(pd)),
373 				em_pd_nr_perf_states(pd->em_pd));
374 		pd = pd->next;
375 	}
376 
377 	printk(KERN_CONT "\n");
378 }
379 
380 static void destroy_perf_domain_rcu(struct rcu_head *rp)
381 {
382 	struct perf_domain *pd;
383 
384 	pd = container_of(rp, struct perf_domain, rcu);
385 	free_pd(pd);
386 }
387 
388 static void sched_energy_set(bool has_eas)
389 {
390 	if (!has_eas && static_branch_unlikely(&sched_energy_present)) {
391 		if (sched_debug())
392 			pr_info("%s: stopping EAS\n", __func__);
393 		static_branch_disable_cpuslocked(&sched_energy_present);
394 	} else if (has_eas && !static_branch_unlikely(&sched_energy_present)) {
395 		if (sched_debug())
396 			pr_info("%s: starting EAS\n", __func__);
397 		static_branch_enable_cpuslocked(&sched_energy_present);
398 	}
399 }
400 
401 /*
402  * EAS can be used on a root domain if it meets all the following conditions:
403  *    1. an Energy Model (EM) is available;
404  *    2. the SD_ASYM_CPUCAPACITY flag is set in the sched_domain hierarchy.
405  *    3. no SMT is detected.
406  *    4. schedutil is driving the frequency of all CPUs of the rd;
407  *    5. frequency invariance support is present;
408  */
409 static bool build_perf_domains(const struct cpumask *cpu_map)
410 {
411 	int i;
412 	struct perf_domain *pd = NULL, *tmp;
413 	int cpu = cpumask_first(cpu_map);
414 	struct root_domain *rd = cpu_rq(cpu)->rd;
415 
416 	if (!sysctl_sched_energy_aware)
417 		goto free;
418 
419 	if (!sched_is_eas_possible(cpu_map))
420 		goto free;
421 
422 	for_each_cpu(i, cpu_map) {
423 		/* Skip already covered CPUs. */
424 		if (find_pd(pd, i))
425 			continue;
426 
427 		/* Create the new pd and add it to the local list. */
428 		tmp = pd_init(i);
429 		if (!tmp)
430 			goto free;
431 		tmp->next = pd;
432 		pd = tmp;
433 	}
434 
435 	perf_domain_debug(cpu_map, pd);
436 
437 	/* Attach the new list of performance domains to the root domain. */
438 	tmp = rd->pd;
439 	rcu_assign_pointer(rd->pd, pd);
440 	if (tmp)
441 		call_rcu(&tmp->rcu, destroy_perf_domain_rcu);
442 
443 	return !!pd;
444 
445 free:
446 	free_pd(pd);
447 	tmp = rd->pd;
448 	rcu_assign_pointer(rd->pd, NULL);
449 	if (tmp)
450 		call_rcu(&tmp->rcu, destroy_perf_domain_rcu);
451 
452 	return false;
453 }
454 #else /* !(CONFIG_ENERGY_MODEL && CONFIG_CPU_FREQ_GOV_SCHEDUTIL): */
455 static void free_pd(struct perf_domain *pd) { }
456 #endif /* !(CONFIG_ENERGY_MODEL && CONFIG_CPU_FREQ_GOV_SCHEDUTIL) */
457 
458 static void free_rootdomain(struct rcu_head *rcu)
459 {
460 	struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
461 
462 	cpupri_cleanup(&rd->cpupri);
463 	cpudl_cleanup(&rd->cpudl);
464 	free_cpumask_var(rd->dlo_mask);
465 	free_cpumask_var(rd->rto_mask);
466 	free_cpumask_var(rd->online);
467 	free_cpumask_var(rd->span);
468 	free_pd(rd->pd);
469 	kfree(rd);
470 }
471 
472 void rq_attach_root(struct rq *rq, struct root_domain *rd)
473 {
474 	struct root_domain *old_rd = NULL;
475 	struct rq_flags rf;
476 
477 	rq_lock_irqsave(rq, &rf);
478 
479 	if (rq->rd) {
480 		old_rd = rq->rd;
481 
482 		if (cpumask_test_cpu(rq->cpu, old_rd->online))
483 			set_rq_offline(rq);
484 
485 		cpumask_clear_cpu(rq->cpu, old_rd->span);
486 
487 		/*
488 		 * If we don't want to free the old_rd yet then
489 		 * set old_rd to NULL to skip the freeing later
490 		 * in this function:
491 		 */
492 		if (!atomic_dec_and_test(&old_rd->refcount))
493 			old_rd = NULL;
494 	}
495 
496 	atomic_inc(&rd->refcount);
497 	rq->rd = rd;
498 
499 	cpumask_set_cpu(rq->cpu, rd->span);
500 	if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
501 		set_rq_online(rq);
502 
503 	/*
504 	 * Because the rq is not a task, dl_add_task_root_domain() did not
505 	 * move the fair server bw to the rd if it already started.
506 	 * Add it now.
507 	 */
508 	if (rq->fair_server.dl_server)
509 		__dl_server_attach_root(&rq->fair_server, rq);
510 
511 #ifdef CONFIG_SCHED_CLASS_EXT
512 	if (rq->ext_server.dl_server)
513 		__dl_server_attach_root(&rq->ext_server, rq);
514 #endif
515 
516 	rq_unlock_irqrestore(rq, &rf);
517 
518 	if (old_rd)
519 		call_rcu(&old_rd->rcu, free_rootdomain);
520 }
521 
522 void sched_get_rd(struct root_domain *rd)
523 {
524 	atomic_inc(&rd->refcount);
525 }
526 
527 void sched_put_rd(struct root_domain *rd)
528 {
529 	if (!atomic_dec_and_test(&rd->refcount))
530 		return;
531 
532 	call_rcu(&rd->rcu, free_rootdomain);
533 }
534 
535 static int init_rootdomain(struct root_domain *rd)
536 {
537 	if (!zalloc_cpumask_var(&rd->span, GFP_KERNEL))
538 		goto out;
539 	if (!zalloc_cpumask_var(&rd->online, GFP_KERNEL))
540 		goto free_span;
541 	if (!zalloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
542 		goto free_online;
543 	if (!zalloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
544 		goto free_dlo_mask;
545 
546 #ifdef HAVE_RT_PUSH_IPI
547 	rd->rto_cpu = -1;
548 	raw_spin_lock_init(&rd->rto_lock);
549 	rd->rto_push_work = IRQ_WORK_INIT_HARD(rto_push_irq_work_func);
550 #endif
551 
552 	rd->visit_cookie = 0;
553 	init_dl_bw(&rd->dl_bw);
554 	if (cpudl_init(&rd->cpudl) != 0)
555 		goto free_rto_mask;
556 
557 	if (cpupri_init(&rd->cpupri) != 0)
558 		goto free_cpudl;
559 	return 0;
560 
561 free_cpudl:
562 	cpudl_cleanup(&rd->cpudl);
563 free_rto_mask:
564 	free_cpumask_var(rd->rto_mask);
565 free_dlo_mask:
566 	free_cpumask_var(rd->dlo_mask);
567 free_online:
568 	free_cpumask_var(rd->online);
569 free_span:
570 	free_cpumask_var(rd->span);
571 out:
572 	return -ENOMEM;
573 }
574 
575 /*
576  * By default the system creates a single root-domain with all CPUs as
577  * members (mimicking the global state we have today).
578  */
579 struct root_domain def_root_domain;
580 
581 void __init init_defrootdomain(void)
582 {
583 	init_rootdomain(&def_root_domain);
584 
585 	atomic_set(&def_root_domain.refcount, 1);
586 }
587 
588 static struct root_domain *alloc_rootdomain(void)
589 {
590 	struct root_domain *rd;
591 
592 	rd = kzalloc(sizeof(*rd), GFP_KERNEL);
593 	if (!rd)
594 		return NULL;
595 
596 	if (init_rootdomain(rd) != 0) {
597 		kfree(rd);
598 		return NULL;
599 	}
600 
601 	return rd;
602 }
603 
604 static void free_sched_groups(struct sched_group *sg, int free_sgc)
605 {
606 	struct sched_group *tmp, *first;
607 
608 	if (!sg)
609 		return;
610 
611 	first = sg;
612 	do {
613 		tmp = sg->next;
614 
615 		if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
616 			kfree(sg->sgc);
617 
618 		if (atomic_dec_and_test(&sg->ref))
619 			kfree(sg);
620 		sg = tmp;
621 	} while (sg != first);
622 }
623 
624 static void destroy_sched_domain(struct sched_domain *sd)
625 {
626 	/*
627 	 * A normal sched domain may have multiple group references, an
628 	 * overlapping domain, having private groups, only one.  Iterate,
629 	 * dropping group/capacity references, freeing where none remain.
630 	 */
631 	free_sched_groups(sd->groups, 1);
632 
633 	if (sd->shared && atomic_dec_and_test(&sd->shared->ref))
634 		kfree(sd->shared);
635 	kfree(sd);
636 }
637 
638 static void destroy_sched_domains_rcu(struct rcu_head *rcu)
639 {
640 	struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
641 
642 	while (sd) {
643 		struct sched_domain *parent = sd->parent;
644 		destroy_sched_domain(sd);
645 		sd = parent;
646 	}
647 }
648 
649 static void destroy_sched_domains(struct sched_domain *sd)
650 {
651 	if (sd)
652 		call_rcu(&sd->rcu, destroy_sched_domains_rcu);
653 }
654 
655 /*
656  * Keep a special pointer to the highest sched_domain that has SD_SHARE_LLC set
657  * (Last Level Cache Domain) for this allows us to avoid some pointer chasing
658  * select_idle_sibling().
659  *
660  * Also keep a unique ID per domain (we use the first CPU number in the cpumask
661  * of the domain), this allows us to quickly tell if two CPUs are in the same
662  * cache domain, see cpus_share_cache().
663  */
664 DEFINE_PER_CPU(struct sched_domain __rcu *, sd_llc);
665 DEFINE_PER_CPU(int, sd_llc_size);
666 DEFINE_PER_CPU(int, sd_llc_id);
667 DEFINE_PER_CPU(int, sd_share_id);
668 DEFINE_PER_CPU(struct sched_domain_shared __rcu *, sd_llc_shared);
669 DEFINE_PER_CPU(struct sched_domain __rcu *, sd_numa);
670 DEFINE_PER_CPU(struct sched_domain __rcu *, sd_asym_packing);
671 DEFINE_PER_CPU(struct sched_domain __rcu *, sd_asym_cpucapacity);
672 
673 DEFINE_STATIC_KEY_FALSE(sched_asym_cpucapacity);
674 DEFINE_STATIC_KEY_FALSE(sched_cluster_active);
675 
676 static void update_top_cache_domain(int cpu)
677 {
678 	struct sched_domain_shared *sds = NULL;
679 	struct sched_domain *sd;
680 	int id = cpu;
681 	int size = 1;
682 
683 	sd = highest_flag_domain(cpu, SD_SHARE_LLC);
684 	if (sd) {
685 		id = cpumask_first(sched_domain_span(sd));
686 		size = cpumask_weight(sched_domain_span(sd));
687 		sds = sd->shared;
688 	}
689 
690 	rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
691 	per_cpu(sd_llc_size, cpu) = size;
692 	per_cpu(sd_llc_id, cpu) = id;
693 	rcu_assign_pointer(per_cpu(sd_llc_shared, cpu), sds);
694 
695 	sd = lowest_flag_domain(cpu, SD_CLUSTER);
696 	if (sd)
697 		id = cpumask_first(sched_domain_span(sd));
698 
699 	/*
700 	 * This assignment should be placed after the sd_llc_id as
701 	 * we want this id equals to cluster id on cluster machines
702 	 * but equals to LLC id on non-Cluster machines.
703 	 */
704 	per_cpu(sd_share_id, cpu) = id;
705 
706 	sd = lowest_flag_domain(cpu, SD_NUMA);
707 	rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
708 
709 	sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
710 	rcu_assign_pointer(per_cpu(sd_asym_packing, cpu), sd);
711 
712 	sd = lowest_flag_domain(cpu, SD_ASYM_CPUCAPACITY_FULL);
713 	rcu_assign_pointer(per_cpu(sd_asym_cpucapacity, cpu), sd);
714 }
715 
716 /*
717  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
718  * hold the hotplug lock.
719  */
720 static void
721 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
722 {
723 	struct rq *rq = cpu_rq(cpu);
724 	struct sched_domain *tmp;
725 
726 	/* Remove the sched domains which do not contribute to scheduling. */
727 	for (tmp = sd; tmp; ) {
728 		struct sched_domain *parent = tmp->parent;
729 		if (!parent)
730 			break;
731 
732 		if (sd_parent_degenerate(tmp, parent)) {
733 			tmp->parent = parent->parent;
734 
735 			if (parent->parent) {
736 				parent->parent->child = tmp;
737 				parent->parent->groups->flags = tmp->flags;
738 			}
739 
740 			/*
741 			 * Transfer SD_PREFER_SIBLING down in case of a
742 			 * degenerate parent; the spans match for this
743 			 * so the property transfers.
744 			 */
745 			if (parent->flags & SD_PREFER_SIBLING)
746 				tmp->flags |= SD_PREFER_SIBLING;
747 			destroy_sched_domain(parent);
748 		} else
749 			tmp = tmp->parent;
750 	}
751 
752 	if (sd && sd_degenerate(sd)) {
753 		tmp = sd;
754 		sd = sd->parent;
755 		destroy_sched_domain(tmp);
756 		if (sd) {
757 			struct sched_group *sg = sd->groups;
758 
759 			/*
760 			 * sched groups hold the flags of the child sched
761 			 * domain for convenience. Clear such flags since
762 			 * the child is being destroyed.
763 			 */
764 			do {
765 				sg->flags = 0;
766 			} while (sg != sd->groups);
767 
768 			sd->child = NULL;
769 		}
770 	}
771 
772 	sched_domain_debug(sd, cpu);
773 
774 	rq_attach_root(rq, rd);
775 	tmp = rq->sd;
776 	rcu_assign_pointer(rq->sd, sd);
777 	dirty_sched_domain_sysctl(cpu);
778 	destroy_sched_domains(tmp);
779 
780 	update_top_cache_domain(cpu);
781 }
782 
783 struct s_data {
784 	struct sched_domain * __percpu *sd;
785 	struct root_domain	*rd;
786 };
787 
788 enum s_alloc {
789 	sa_rootdomain,
790 	sa_sd,
791 	sa_sd_storage,
792 	sa_none,
793 };
794 
795 /*
796  * Return the canonical balance CPU for this group, this is the first CPU
797  * of this group that's also in the balance mask.
798  *
799  * The balance mask are all those CPUs that could actually end up at this
800  * group. See build_balance_mask().
801  *
802  * Also see should_we_balance().
803  */
804 int group_balance_cpu(struct sched_group *sg)
805 {
806 	return cpumask_first(group_balance_mask(sg));
807 }
808 
809 
810 /*
811  * NUMA topology (first read the regular topology blurb below)
812  *
813  * Given a node-distance table, for example:
814  *
815  *   node   0   1   2   3
816  *     0:  10  20  30  20
817  *     1:  20  10  20  30
818  *     2:  30  20  10  20
819  *     3:  20  30  20  10
820  *
821  * which represents a 4 node ring topology like:
822  *
823  *   0 ----- 1
824  *   |       |
825  *   |       |
826  *   |       |
827  *   3 ----- 2
828  *
829  * We want to construct domains and groups to represent this. The way we go
830  * about doing this is to build the domains on 'hops'. For each NUMA level we
831  * construct the mask of all nodes reachable in @level hops.
832  *
833  * For the above NUMA topology that gives 3 levels:
834  *
835  * NUMA-2	0-3		0-3		0-3		0-3
836  *  groups:	{0-1,3},{1-3}	{0-2},{0,2-3}	{1-3},{0-1,3}	{0,2-3},{0-2}
837  *
838  * NUMA-1	0-1,3		0-2		1-3		0,2-3
839  *  groups:	{0},{1},{3}	{0},{1},{2}	{1},{2},{3}	{0},{2},{3}
840  *
841  * NUMA-0	0		1		2		3
842  *
843  *
844  * As can be seen; things don't nicely line up as with the regular topology.
845  * When we iterate a domain in child domain chunks some nodes can be
846  * represented multiple times -- hence the "overlap" naming for this part of
847  * the topology.
848  *
849  * In order to minimize this overlap, we only build enough groups to cover the
850  * domain. For instance Node-0 NUMA-2 would only get groups: 0-1,3 and 1-3.
851  *
852  * Because:
853  *
854  *  - the first group of each domain is its child domain; this
855  *    gets us the first 0-1,3
856  *  - the only uncovered node is 2, who's child domain is 1-3.
857  *
858  * However, because of the overlap, computing a unique CPU for each group is
859  * more complicated. Consider for instance the groups of NODE-1 NUMA-2, both
860  * groups include the CPUs of Node-0, while those CPUs would not in fact ever
861  * end up at those groups (they would end up in group: 0-1,3).
862  *
863  * To correct this we have to introduce the group balance mask. This mask
864  * will contain those CPUs in the group that can reach this group given the
865  * (child) domain tree.
866  *
867  * With this we can once again compute balance_cpu and sched_group_capacity
868  * relations.
869  *
870  * XXX include words on how balance_cpu is unique and therefore can be
871  * used for sched_group_capacity links.
872  *
873  *
874  * Another 'interesting' topology is:
875  *
876  *   node   0   1   2   3
877  *     0:  10  20  20  30
878  *     1:  20  10  20  20
879  *     2:  20  20  10  20
880  *     3:  30  20  20  10
881  *
882  * Which looks a little like:
883  *
884  *   0 ----- 1
885  *   |     / |
886  *   |   /   |
887  *   | /     |
888  *   2 ----- 3
889  *
890  * This topology is asymmetric, nodes 1,2 are fully connected, but nodes 0,3
891  * are not.
892  *
893  * This leads to a few particularly weird cases where the sched_domain's are
894  * not of the same number for each CPU. Consider:
895  *
896  * NUMA-2	0-3						0-3
897  *  groups:	{0-2},{1-3}					{1-3},{0-2}
898  *
899  * NUMA-1	0-2		0-3		0-3		1-3
900  *
901  * NUMA-0	0		1		2		3
902  *
903  */
904 
905 
906 /*
907  * Build the balance mask; it contains only those CPUs that can arrive at this
908  * group and should be considered to continue balancing.
909  *
910  * We do this during the group creation pass, therefore the group information
911  * isn't complete yet, however since each group represents a (child) domain we
912  * can fully construct this using the sched_domain bits (which are already
913  * complete).
914  */
915 static void
916 build_balance_mask(struct sched_domain *sd, struct sched_group *sg, struct cpumask *mask)
917 {
918 	const struct cpumask *sg_span = sched_group_span(sg);
919 	struct sd_data *sdd = sd->private;
920 	struct sched_domain *sibling;
921 	int i;
922 
923 	cpumask_clear(mask);
924 
925 	for_each_cpu(i, sg_span) {
926 		sibling = *per_cpu_ptr(sdd->sd, i);
927 
928 		/*
929 		 * Can happen in the asymmetric case, where these siblings are
930 		 * unused. The mask will not be empty because those CPUs that
931 		 * do have the top domain _should_ span the domain.
932 		 */
933 		if (!sibling->child)
934 			continue;
935 
936 		/* If we would not end up here, we can't continue from here */
937 		if (!cpumask_equal(sg_span, sched_domain_span(sibling->child)))
938 			continue;
939 
940 		cpumask_set_cpu(i, mask);
941 	}
942 
943 	/* We must not have empty masks here */
944 	WARN_ON_ONCE(cpumask_empty(mask));
945 }
946 
947 /*
948  * XXX: This creates per-node group entries; since the load-balancer will
949  * immediately access remote memory to construct this group's load-balance
950  * statistics having the groups node local is of dubious benefit.
951  */
952 static struct sched_group *
953 build_group_from_child_sched_domain(struct sched_domain *sd, int cpu)
954 {
955 	struct sched_group *sg;
956 	struct cpumask *sg_span;
957 
958 	sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
959 			GFP_KERNEL, cpu_to_node(cpu));
960 
961 	if (!sg)
962 		return NULL;
963 
964 	sg_span = sched_group_span(sg);
965 	if (sd->child) {
966 		cpumask_copy(sg_span, sched_domain_span(sd->child));
967 		sg->flags = sd->child->flags;
968 	} else {
969 		cpumask_copy(sg_span, sched_domain_span(sd));
970 	}
971 
972 	atomic_inc(&sg->ref);
973 	return sg;
974 }
975 
976 static void init_overlap_sched_group(struct sched_domain *sd,
977 				     struct sched_group *sg)
978 {
979 	struct cpumask *mask = sched_domains_tmpmask2;
980 	struct sd_data *sdd = sd->private;
981 	struct cpumask *sg_span;
982 	int cpu;
983 
984 	build_balance_mask(sd, sg, mask);
985 	cpu = cpumask_first(mask);
986 
987 	sg->sgc = *per_cpu_ptr(sdd->sgc, cpu);
988 	if (atomic_inc_return(&sg->sgc->ref) == 1)
989 		cpumask_copy(group_balance_mask(sg), mask);
990 	else
991 		WARN_ON_ONCE(!cpumask_equal(group_balance_mask(sg), mask));
992 
993 	/*
994 	 * Initialize sgc->capacity such that even if we mess up the
995 	 * domains and no possible iteration will get us here, we won't
996 	 * die on a /0 trap.
997 	 */
998 	sg_span = sched_group_span(sg);
999 	sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
1000 	sg->sgc->min_capacity = SCHED_CAPACITY_SCALE;
1001 	sg->sgc->max_capacity = SCHED_CAPACITY_SCALE;
1002 }
1003 
1004 static struct sched_domain *
1005 find_descended_sibling(struct sched_domain *sd, struct sched_domain *sibling)
1006 {
1007 	/*
1008 	 * The proper descendant would be the one whose child won't span out
1009 	 * of sd
1010 	 */
1011 	while (sibling->child &&
1012 	       !cpumask_subset(sched_domain_span(sibling->child),
1013 			       sched_domain_span(sd)))
1014 		sibling = sibling->child;
1015 
1016 	/*
1017 	 * As we are referencing sgc across different topology level, we need
1018 	 * to go down to skip those sched_domains which don't contribute to
1019 	 * scheduling because they will be degenerated in cpu_attach_domain
1020 	 */
1021 	while (sibling->child &&
1022 	       cpumask_equal(sched_domain_span(sibling->child),
1023 			     sched_domain_span(sibling)))
1024 		sibling = sibling->child;
1025 
1026 	return sibling;
1027 }
1028 
1029 static int
1030 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
1031 {
1032 	struct sched_group *first = NULL, *last = NULL, *sg;
1033 	const struct cpumask *span = sched_domain_span(sd);
1034 	struct cpumask *covered = sched_domains_tmpmask;
1035 	struct sd_data *sdd = sd->private;
1036 	struct sched_domain *sibling;
1037 	int i;
1038 
1039 	cpumask_clear(covered);
1040 
1041 	for_each_cpu_wrap(i, span, cpu) {
1042 		struct cpumask *sg_span;
1043 
1044 		if (cpumask_test_cpu(i, covered))
1045 			continue;
1046 
1047 		sibling = *per_cpu_ptr(sdd->sd, i);
1048 
1049 		/*
1050 		 * Asymmetric node setups can result in situations where the
1051 		 * domain tree is of unequal depth, make sure to skip domains
1052 		 * that already cover the entire range.
1053 		 *
1054 		 * In that case build_sched_domains() will have terminated the
1055 		 * iteration early and our sibling sd spans will be empty.
1056 		 * Domains should always include the CPU they're built on, so
1057 		 * check that.
1058 		 */
1059 		if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
1060 			continue;
1061 
1062 		/*
1063 		 * Usually we build sched_group by sibling's child sched_domain
1064 		 * But for machines whose NUMA diameter are 3 or above, we move
1065 		 * to build sched_group by sibling's proper descendant's child
1066 		 * domain because sibling's child sched_domain will span out of
1067 		 * the sched_domain being built as below.
1068 		 *
1069 		 * Smallest diameter=3 topology is:
1070 		 *
1071 		 *   node   0   1   2   3
1072 		 *     0:  10  20  30  40
1073 		 *     1:  20  10  20  30
1074 		 *     2:  30  20  10  20
1075 		 *     3:  40  30  20  10
1076 		 *
1077 		 *   0 --- 1 --- 2 --- 3
1078 		 *
1079 		 * NUMA-3       0-3             N/A             N/A             0-3
1080 		 *  groups:     {0-2},{1-3}                                     {1-3},{0-2}
1081 		 *
1082 		 * NUMA-2       0-2             0-3             0-3             1-3
1083 		 *  groups:     {0-1},{1-3}     {0-2},{2-3}     {1-3},{0-1}     {2-3},{0-2}
1084 		 *
1085 		 * NUMA-1       0-1             0-2             1-3             2-3
1086 		 *  groups:     {0},{1}         {1},{2},{0}     {2},{3},{1}     {3},{2}
1087 		 *
1088 		 * NUMA-0       0               1               2               3
1089 		 *
1090 		 * The NUMA-2 groups for nodes 0 and 3 are obviously buggered, as the
1091 		 * group span isn't a subset of the domain span.
1092 		 */
1093 		if (sibling->child &&
1094 		    !cpumask_subset(sched_domain_span(sibling->child), span))
1095 			sibling = find_descended_sibling(sd, sibling);
1096 
1097 		sg = build_group_from_child_sched_domain(sibling, cpu);
1098 		if (!sg)
1099 			goto fail;
1100 
1101 		sg_span = sched_group_span(sg);
1102 		cpumask_or(covered, covered, sg_span);
1103 
1104 		init_overlap_sched_group(sibling, sg);
1105 
1106 		if (!first)
1107 			first = sg;
1108 		if (last)
1109 			last->next = sg;
1110 		last = sg;
1111 		last->next = first;
1112 	}
1113 	sd->groups = first;
1114 
1115 	return 0;
1116 
1117 fail:
1118 	free_sched_groups(first, 0);
1119 
1120 	return -ENOMEM;
1121 }
1122 
1123 
1124 /*
1125  * Package topology (also see the load-balance blurb in fair.c)
1126  *
1127  * The scheduler builds a tree structure to represent a number of important
1128  * topology features. By default (default_topology[]) these include:
1129  *
1130  *  - Simultaneous multithreading (SMT)
1131  *  - Multi-Core Cache (MC)
1132  *  - Package (PKG)
1133  *
1134  * Where the last one more or less denotes everything up to a NUMA node.
1135  *
1136  * The tree consists of 3 primary data structures:
1137  *
1138  *	sched_domain -> sched_group -> sched_group_capacity
1139  *	    ^ ^             ^ ^
1140  *          `-'             `-'
1141  *
1142  * The sched_domains are per-CPU and have a two way link (parent & child) and
1143  * denote the ever growing mask of CPUs belonging to that level of topology.
1144  *
1145  * Each sched_domain has a circular (double) linked list of sched_group's, each
1146  * denoting the domains of the level below (or individual CPUs in case of the
1147  * first domain level). The sched_group linked by a sched_domain includes the
1148  * CPU of that sched_domain [*].
1149  *
1150  * Take for instance a 2 threaded, 2 core, 2 cache cluster part:
1151  *
1152  * CPU   0   1   2   3   4   5   6   7
1153  *
1154  * PKG  [                             ]
1155  * MC   [             ] [             ]
1156  * SMT  [     ] [     ] [     ] [     ]
1157  *
1158  *  - or -
1159  *
1160  * PKG  0-7 0-7 0-7 0-7 0-7 0-7 0-7 0-7
1161  * MC	0-3 0-3 0-3 0-3 4-7 4-7 4-7 4-7
1162  * SMT  0-1 0-1 2-3 2-3 4-5 4-5 6-7 6-7
1163  *
1164  * CPU   0   1   2   3   4   5   6   7
1165  *
1166  * One way to think about it is: sched_domain moves you up and down among these
1167  * topology levels, while sched_group moves you sideways through it, at child
1168  * domain granularity.
1169  *
1170  * sched_group_capacity ensures each unique sched_group has shared storage.
1171  *
1172  * There are two related construction problems, both require a CPU that
1173  * uniquely identify each group (for a given domain):
1174  *
1175  *  - The first is the balance_cpu (see should_we_balance() and the
1176  *    load-balance blurb in fair.c); for each group we only want 1 CPU to
1177  *    continue balancing at a higher domain.
1178  *
1179  *  - The second is the sched_group_capacity; we want all identical groups
1180  *    to share a single sched_group_capacity.
1181  *
1182  * Since these topologies are exclusive by construction. That is, its
1183  * impossible for an SMT thread to belong to multiple cores, and cores to
1184  * be part of multiple caches. There is a very clear and unique location
1185  * for each CPU in the hierarchy.
1186  *
1187  * Therefore computing a unique CPU for each group is trivial (the iteration
1188  * mask is redundant and set all 1s; all CPUs in a group will end up at _that_
1189  * group), we can simply pick the first CPU in each group.
1190  *
1191  *
1192  * [*] in other words, the first group of each domain is its child domain.
1193  */
1194 
1195 static struct sched_group *get_group(int cpu, struct sd_data *sdd)
1196 {
1197 	struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
1198 	struct sched_domain *child = sd->child;
1199 	struct sched_group *sg;
1200 	bool already_visited;
1201 
1202 	if (child)
1203 		cpu = cpumask_first(sched_domain_span(child));
1204 
1205 	sg = *per_cpu_ptr(sdd->sg, cpu);
1206 	sg->sgc = *per_cpu_ptr(sdd->sgc, cpu);
1207 
1208 	/* Increase refcounts for claim_allocations: */
1209 	already_visited = atomic_inc_return(&sg->ref) > 1;
1210 	/* sgc visits should follow a similar trend as sg */
1211 	WARN_ON(already_visited != (atomic_inc_return(&sg->sgc->ref) > 1));
1212 
1213 	/* If we have already visited that group, it's already initialized. */
1214 	if (already_visited)
1215 		return sg;
1216 
1217 	if (child) {
1218 		cpumask_copy(sched_group_span(sg), sched_domain_span(child));
1219 		cpumask_copy(group_balance_mask(sg), sched_group_span(sg));
1220 		sg->flags = child->flags;
1221 	} else {
1222 		cpumask_set_cpu(cpu, sched_group_span(sg));
1223 		cpumask_set_cpu(cpu, group_balance_mask(sg));
1224 	}
1225 
1226 	sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sched_group_span(sg));
1227 	sg->sgc->min_capacity = SCHED_CAPACITY_SCALE;
1228 	sg->sgc->max_capacity = SCHED_CAPACITY_SCALE;
1229 
1230 	return sg;
1231 }
1232 
1233 /*
1234  * build_sched_groups will build a circular linked list of the groups
1235  * covered by the given span, will set each group's ->cpumask correctly,
1236  * and will initialize their ->sgc.
1237  *
1238  * Assumes the sched_domain tree is fully constructed
1239  */
1240 static int
1241 build_sched_groups(struct sched_domain *sd, int cpu)
1242 {
1243 	struct sched_group *first = NULL, *last = NULL;
1244 	struct sd_data *sdd = sd->private;
1245 	const struct cpumask *span = sched_domain_span(sd);
1246 	struct cpumask *covered;
1247 	int i;
1248 
1249 	lockdep_assert_held(&sched_domains_mutex);
1250 	covered = sched_domains_tmpmask;
1251 
1252 	cpumask_clear(covered);
1253 
1254 	for_each_cpu_wrap(i, span, cpu) {
1255 		struct sched_group *sg;
1256 
1257 		if (cpumask_test_cpu(i, covered))
1258 			continue;
1259 
1260 		sg = get_group(i, sdd);
1261 
1262 		cpumask_or(covered, covered, sched_group_span(sg));
1263 
1264 		if (!first)
1265 			first = sg;
1266 		if (last)
1267 			last->next = sg;
1268 		last = sg;
1269 	}
1270 	last->next = first;
1271 	sd->groups = first;
1272 
1273 	return 0;
1274 }
1275 
1276 /*
1277  * Initialize sched groups cpu_capacity.
1278  *
1279  * cpu_capacity indicates the capacity of sched group, which is used while
1280  * distributing the load between different sched groups in a sched domain.
1281  * Typically cpu_capacity for all the groups in a sched domain will be same
1282  * unless there are asymmetries in the topology. If there are asymmetries,
1283  * group having more cpu_capacity will pickup more load compared to the
1284  * group having less cpu_capacity.
1285  */
1286 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
1287 {
1288 	struct sched_group *sg = sd->groups;
1289 	struct cpumask *mask = sched_domains_tmpmask2;
1290 
1291 	WARN_ON(!sg);
1292 
1293 	do {
1294 		int cpu, cores = 0, max_cpu = -1;
1295 
1296 		sg->group_weight = cpumask_weight(sched_group_span(sg));
1297 
1298 		cpumask_copy(mask, sched_group_span(sg));
1299 		for_each_cpu(cpu, mask) {
1300 			cores++;
1301 #ifdef CONFIG_SCHED_SMT
1302 			cpumask_andnot(mask, mask, cpu_smt_mask(cpu));
1303 #endif
1304 		}
1305 		sg->cores = cores;
1306 
1307 		if (!(sd->flags & SD_ASYM_PACKING))
1308 			goto next;
1309 
1310 		for_each_cpu(cpu, sched_group_span(sg)) {
1311 			if (max_cpu < 0)
1312 				max_cpu = cpu;
1313 			else if (sched_asym_prefer(cpu, max_cpu))
1314 				max_cpu = cpu;
1315 		}
1316 		sg->asym_prefer_cpu = max_cpu;
1317 
1318 next:
1319 		sg = sg->next;
1320 	} while (sg != sd->groups);
1321 
1322 	if (cpu != group_balance_cpu(sg))
1323 		return;
1324 
1325 	update_group_capacity(sd, cpu);
1326 }
1327 
1328 /* Update the "asym_prefer_cpu" when arch_asym_cpu_priority() changes. */
1329 void sched_update_asym_prefer_cpu(int cpu, int old_prio, int new_prio)
1330 {
1331 	int asym_prefer_cpu = cpu;
1332 	struct sched_domain *sd;
1333 
1334 	guard(rcu)();
1335 
1336 	for_each_domain(cpu, sd) {
1337 		struct sched_group *sg;
1338 		int group_cpu;
1339 
1340 		if (!(sd->flags & SD_ASYM_PACKING))
1341 			continue;
1342 
1343 		/*
1344 		 * Groups of overlapping domain are replicated per NUMA
1345 		 * node and will require updating "asym_prefer_cpu" on
1346 		 * each local copy.
1347 		 *
1348 		 * If you are hitting this warning, consider moving
1349 		 * "sg->asym_prefer_cpu" to "sg->sgc->asym_prefer_cpu"
1350 		 * which is shared by all the overlapping groups.
1351 		 */
1352 		WARN_ON_ONCE(sd->flags & SD_NUMA);
1353 
1354 		sg = sd->groups;
1355 		if (cpu != sg->asym_prefer_cpu) {
1356 			/*
1357 			 * Since the parent is a superset of the current group,
1358 			 * if the cpu is not the "asym_prefer_cpu" at the
1359 			 * current level, it cannot be the preferred CPU at a
1360 			 * higher levels either.
1361 			 */
1362 			if (!sched_asym_prefer(cpu, sg->asym_prefer_cpu))
1363 				return;
1364 
1365 			WRITE_ONCE(sg->asym_prefer_cpu, cpu);
1366 			continue;
1367 		}
1368 
1369 		/* Ranking has improved; CPU is still the preferred one. */
1370 		if (new_prio >= old_prio)
1371 			continue;
1372 
1373 		for_each_cpu(group_cpu, sched_group_span(sg)) {
1374 			if (sched_asym_prefer(group_cpu, asym_prefer_cpu))
1375 				asym_prefer_cpu = group_cpu;
1376 		}
1377 
1378 		WRITE_ONCE(sg->asym_prefer_cpu, asym_prefer_cpu);
1379 	}
1380 }
1381 
1382 /*
1383  * Set of available CPUs grouped by their corresponding capacities
1384  * Each list entry contains a CPU mask reflecting CPUs that share the same
1385  * capacity.
1386  * The lifespan of data is unlimited.
1387  */
1388 LIST_HEAD(asym_cap_list);
1389 
1390 /*
1391  * Verify whether there is any CPU capacity asymmetry in a given sched domain.
1392  * Provides sd_flags reflecting the asymmetry scope.
1393  */
1394 static inline int
1395 asym_cpu_capacity_classify(const struct cpumask *sd_span,
1396 			   const struct cpumask *cpu_map)
1397 {
1398 	struct asym_cap_data *entry;
1399 	int count = 0, miss = 0;
1400 
1401 	/*
1402 	 * Count how many unique CPU capacities this domain spans across
1403 	 * (compare sched_domain CPUs mask with ones representing  available
1404 	 * CPUs capacities). Take into account CPUs that might be offline:
1405 	 * skip those.
1406 	 */
1407 	list_for_each_entry(entry, &asym_cap_list, link) {
1408 		if (cpumask_intersects(sd_span, cpu_capacity_span(entry)))
1409 			++count;
1410 		else if (cpumask_intersects(cpu_map, cpu_capacity_span(entry)))
1411 			++miss;
1412 	}
1413 
1414 	WARN_ON_ONCE(!count && !list_empty(&asym_cap_list));
1415 
1416 	/* No asymmetry detected */
1417 	if (count < 2)
1418 		return 0;
1419 	/* Some of the available CPU capacity values have not been detected */
1420 	if (miss)
1421 		return SD_ASYM_CPUCAPACITY;
1422 
1423 	/* Full asymmetry */
1424 	return SD_ASYM_CPUCAPACITY | SD_ASYM_CPUCAPACITY_FULL;
1425 
1426 }
1427 
1428 static void free_asym_cap_entry(struct rcu_head *head)
1429 {
1430 	struct asym_cap_data *entry = container_of(head, struct asym_cap_data, rcu);
1431 	kfree(entry);
1432 }
1433 
1434 static inline void asym_cpu_capacity_update_data(int cpu)
1435 {
1436 	unsigned long capacity = arch_scale_cpu_capacity(cpu);
1437 	struct asym_cap_data *insert_entry = NULL;
1438 	struct asym_cap_data *entry;
1439 
1440 	/*
1441 	 * Search if capacity already exits. If not, track which the entry
1442 	 * where we should insert to keep the list ordered descending.
1443 	 */
1444 	list_for_each_entry(entry, &asym_cap_list, link) {
1445 		if (capacity == entry->capacity)
1446 			goto done;
1447 		else if (!insert_entry && capacity > entry->capacity)
1448 			insert_entry = list_prev_entry(entry, link);
1449 	}
1450 
1451 	entry = kzalloc(sizeof(*entry) + cpumask_size(), GFP_KERNEL);
1452 	if (WARN_ONCE(!entry, "Failed to allocate memory for asymmetry data\n"))
1453 		return;
1454 	entry->capacity = capacity;
1455 
1456 	/* If NULL then the new capacity is the smallest, add last. */
1457 	if (!insert_entry)
1458 		list_add_tail_rcu(&entry->link, &asym_cap_list);
1459 	else
1460 		list_add_rcu(&entry->link, &insert_entry->link);
1461 done:
1462 	__cpumask_set_cpu(cpu, cpu_capacity_span(entry));
1463 }
1464 
1465 /*
1466  * Build-up/update list of CPUs grouped by their capacities
1467  * An update requires explicit request to rebuild sched domains
1468  * with state indicating CPU topology changes.
1469  */
1470 static void asym_cpu_capacity_scan(void)
1471 {
1472 	struct asym_cap_data *entry, *next;
1473 	int cpu;
1474 
1475 	list_for_each_entry(entry, &asym_cap_list, link)
1476 		cpumask_clear(cpu_capacity_span(entry));
1477 
1478 	for_each_cpu_and(cpu, cpu_possible_mask, housekeeping_cpumask(HK_TYPE_DOMAIN))
1479 		asym_cpu_capacity_update_data(cpu);
1480 
1481 	list_for_each_entry_safe(entry, next, &asym_cap_list, link) {
1482 		if (cpumask_empty(cpu_capacity_span(entry))) {
1483 			list_del_rcu(&entry->link);
1484 			call_rcu(&entry->rcu, free_asym_cap_entry);
1485 		}
1486 	}
1487 
1488 	/*
1489 	 * Only one capacity value has been detected i.e. this system is symmetric.
1490 	 * No need to keep this data around.
1491 	 */
1492 	if (list_is_singular(&asym_cap_list)) {
1493 		entry = list_first_entry(&asym_cap_list, typeof(*entry), link);
1494 		list_del_rcu(&entry->link);
1495 		call_rcu(&entry->rcu, free_asym_cap_entry);
1496 	}
1497 }
1498 
1499 /*
1500  * Initializers for schedule domains
1501  * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
1502  */
1503 
1504 static int default_relax_domain_level = -1;
1505 int sched_domain_level_max;
1506 
1507 static int __init setup_relax_domain_level(char *str)
1508 {
1509 	if (kstrtoint(str, 0, &default_relax_domain_level))
1510 		pr_warn("Unable to set relax_domain_level\n");
1511 
1512 	return 1;
1513 }
1514 __setup("relax_domain_level=", setup_relax_domain_level);
1515 
1516 static void set_domain_attribute(struct sched_domain *sd,
1517 				 struct sched_domain_attr *attr)
1518 {
1519 	int request;
1520 
1521 	if (!attr || attr->relax_domain_level < 0) {
1522 		if (default_relax_domain_level < 0)
1523 			return;
1524 		request = default_relax_domain_level;
1525 	} else
1526 		request = attr->relax_domain_level;
1527 
1528 	if (sd->level >= request) {
1529 		/* Turn off idle balance on this domain: */
1530 		sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
1531 	}
1532 }
1533 
1534 static void __sdt_free(const struct cpumask *cpu_map);
1535 static int __sdt_alloc(const struct cpumask *cpu_map);
1536 
1537 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
1538 				 const struct cpumask *cpu_map)
1539 {
1540 	switch (what) {
1541 	case sa_rootdomain:
1542 		if (!atomic_read(&d->rd->refcount))
1543 			free_rootdomain(&d->rd->rcu);
1544 		fallthrough;
1545 	case sa_sd:
1546 		free_percpu(d->sd);
1547 		fallthrough;
1548 	case sa_sd_storage:
1549 		__sdt_free(cpu_map);
1550 		fallthrough;
1551 	case sa_none:
1552 		break;
1553 	}
1554 }
1555 
1556 static enum s_alloc
1557 __visit_domain_allocation_hell(struct s_data *d, const struct cpumask *cpu_map)
1558 {
1559 	memset(d, 0, sizeof(*d));
1560 
1561 	if (__sdt_alloc(cpu_map))
1562 		return sa_sd_storage;
1563 	d->sd = alloc_percpu(struct sched_domain *);
1564 	if (!d->sd)
1565 		return sa_sd_storage;
1566 	d->rd = alloc_rootdomain();
1567 	if (!d->rd)
1568 		return sa_sd;
1569 
1570 	return sa_rootdomain;
1571 }
1572 
1573 /*
1574  * NULL the sd_data elements we've used to build the sched_domain and
1575  * sched_group structure so that the subsequent __free_domain_allocs()
1576  * will not free the data we're using.
1577  */
1578 static void claim_allocations(int cpu, struct sched_domain *sd)
1579 {
1580 	struct sd_data *sdd = sd->private;
1581 
1582 	WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
1583 	*per_cpu_ptr(sdd->sd, cpu) = NULL;
1584 
1585 	if (atomic_read(&(*per_cpu_ptr(sdd->sds, cpu))->ref))
1586 		*per_cpu_ptr(sdd->sds, cpu) = NULL;
1587 
1588 	if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
1589 		*per_cpu_ptr(sdd->sg, cpu) = NULL;
1590 
1591 	if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
1592 		*per_cpu_ptr(sdd->sgc, cpu) = NULL;
1593 }
1594 
1595 #ifdef CONFIG_NUMA
1596 enum numa_topology_type sched_numa_topology_type;
1597 
1598 /*
1599  * sched_domains_numa_distance is derived from sched_numa_node_distance
1600  * and provides a simplified view of NUMA distances used specifically
1601  * for building NUMA scheduling domains.
1602  */
1603 static int			sched_domains_numa_levels;
1604 static int			sched_numa_node_levels;
1605 
1606 int				sched_max_numa_distance;
1607 static int			*sched_domains_numa_distance;
1608 static int			*sched_numa_node_distance;
1609 static struct cpumask		***sched_domains_numa_masks;
1610 #endif /* CONFIG_NUMA */
1611 
1612 /*
1613  * SD_flags allowed in topology descriptions.
1614  *
1615  * These flags are purely descriptive of the topology and do not prescribe
1616  * behaviour. Behaviour is artificial and mapped in the below sd_init()
1617  * function. For details, see include/linux/sched/sd_flags.h.
1618  *
1619  *   SD_SHARE_CPUCAPACITY
1620  *   SD_SHARE_LLC
1621  *   SD_CLUSTER
1622  *   SD_NUMA
1623  *
1624  * Odd one out, which beside describing the topology has a quirk also
1625  * prescribes the desired behaviour that goes along with it:
1626  *
1627  *   SD_ASYM_PACKING        - describes SMT quirks
1628  */
1629 #define TOPOLOGY_SD_FLAGS		\
1630 	(SD_SHARE_CPUCAPACITY	|	\
1631 	 SD_CLUSTER		|	\
1632 	 SD_SHARE_LLC		|	\
1633 	 SD_NUMA		|	\
1634 	 SD_ASYM_PACKING)
1635 
1636 static struct sched_domain *
1637 sd_init(struct sched_domain_topology_level *tl,
1638 	const struct cpumask *cpu_map,
1639 	struct sched_domain *child, int cpu)
1640 {
1641 	struct sd_data *sdd = &tl->data;
1642 	struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
1643 	int sd_id, sd_weight, sd_flags = 0;
1644 	struct cpumask *sd_span;
1645 
1646 	sd_weight = cpumask_weight(tl->mask(tl, cpu));
1647 
1648 	if (tl->sd_flags)
1649 		sd_flags = (*tl->sd_flags)();
1650 	if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
1651 			"wrong sd_flags in topology description\n"))
1652 		sd_flags &= TOPOLOGY_SD_FLAGS;
1653 
1654 	*sd = (struct sched_domain){
1655 		.min_interval		= sd_weight,
1656 		.max_interval		= 2*sd_weight,
1657 		.busy_factor		= 16,
1658 		.imbalance_pct		= 117,
1659 
1660 		.cache_nice_tries	= 0,
1661 
1662 		.flags			= 1*SD_BALANCE_NEWIDLE
1663 					| 1*SD_BALANCE_EXEC
1664 					| 1*SD_BALANCE_FORK
1665 					| 0*SD_BALANCE_WAKE
1666 					| 1*SD_WAKE_AFFINE
1667 					| 0*SD_SHARE_CPUCAPACITY
1668 					| 0*SD_SHARE_LLC
1669 					| 0*SD_SERIALIZE
1670 					| 1*SD_PREFER_SIBLING
1671 					| 0*SD_NUMA
1672 					| sd_flags
1673 					,
1674 
1675 		.last_balance		= jiffies,
1676 		.balance_interval	= sd_weight,
1677 
1678 		/* 50% success rate */
1679 		.newidle_call		= 512,
1680 		.newidle_success	= 256,
1681 		.newidle_ratio		= 512,
1682 
1683 		.max_newidle_lb_cost	= 0,
1684 		.last_decay_max_lb_cost	= jiffies,
1685 		.child			= child,
1686 		.name			= tl->name,
1687 	};
1688 
1689 	sd_span = sched_domain_span(sd);
1690 	cpumask_and(sd_span, cpu_map, tl->mask(tl, cpu));
1691 	sd_id = cpumask_first(sd_span);
1692 
1693 	sd->flags |= asym_cpu_capacity_classify(sd_span, cpu_map);
1694 
1695 	WARN_ONCE((sd->flags & (SD_SHARE_CPUCAPACITY | SD_ASYM_CPUCAPACITY)) ==
1696 		  (SD_SHARE_CPUCAPACITY | SD_ASYM_CPUCAPACITY),
1697 		  "CPU capacity asymmetry not supported on SMT\n");
1698 
1699 	/*
1700 	 * Convert topological properties into behaviour.
1701 	 */
1702 	/* Don't attempt to spread across CPUs of different capacities. */
1703 	if ((sd->flags & SD_ASYM_CPUCAPACITY) && sd->child)
1704 		sd->child->flags &= ~SD_PREFER_SIBLING;
1705 
1706 	if (sd->flags & SD_SHARE_CPUCAPACITY) {
1707 		sd->imbalance_pct = 110;
1708 
1709 	} else if (sd->flags & SD_SHARE_LLC) {
1710 		sd->imbalance_pct = 117;
1711 		sd->cache_nice_tries = 1;
1712 
1713 #ifdef CONFIG_NUMA
1714 	} else if (sd->flags & SD_NUMA) {
1715 		sd->cache_nice_tries = 2;
1716 
1717 		sd->flags &= ~SD_PREFER_SIBLING;
1718 		sd->flags |= SD_SERIALIZE;
1719 		if (sched_domains_numa_distance[tl->numa_level] > node_reclaim_distance) {
1720 			sd->flags &= ~(SD_BALANCE_EXEC |
1721 				       SD_BALANCE_FORK |
1722 				       SD_WAKE_AFFINE);
1723 		}
1724 
1725 #endif /* CONFIG_NUMA */
1726 	} else {
1727 		sd->cache_nice_tries = 1;
1728 	}
1729 
1730 	/*
1731 	 * For all levels sharing cache; connect a sched_domain_shared
1732 	 * instance.
1733 	 */
1734 	if (sd->flags & SD_SHARE_LLC) {
1735 		sd->shared = *per_cpu_ptr(sdd->sds, sd_id);
1736 		atomic_inc(&sd->shared->ref);
1737 		atomic_set(&sd->shared->nr_busy_cpus, sd_weight);
1738 	}
1739 
1740 	sd->private = sdd;
1741 
1742 	return sd;
1743 }
1744 
1745 #ifdef CONFIG_SCHED_SMT
1746 int cpu_smt_flags(void)
1747 {
1748 	return SD_SHARE_CPUCAPACITY | SD_SHARE_LLC;
1749 }
1750 
1751 const struct cpumask *tl_smt_mask(struct sched_domain_topology_level *tl, int cpu)
1752 {
1753 	return cpu_smt_mask(cpu);
1754 }
1755 #endif
1756 
1757 #ifdef CONFIG_SCHED_CLUSTER
1758 int cpu_cluster_flags(void)
1759 {
1760 	return SD_CLUSTER | SD_SHARE_LLC;
1761 }
1762 
1763 const struct cpumask *tl_cls_mask(struct sched_domain_topology_level *tl, int cpu)
1764 {
1765 	return cpu_clustergroup_mask(cpu);
1766 }
1767 #endif
1768 
1769 #ifdef CONFIG_SCHED_MC
1770 int cpu_core_flags(void)
1771 {
1772 	return SD_SHARE_LLC;
1773 }
1774 
1775 const struct cpumask *tl_mc_mask(struct sched_domain_topology_level *tl, int cpu)
1776 {
1777 	return cpu_coregroup_mask(cpu);
1778 }
1779 #endif
1780 
1781 const struct cpumask *tl_pkg_mask(struct sched_domain_topology_level *tl, int cpu)
1782 {
1783 	return cpu_node_mask(cpu);
1784 }
1785 
1786 /*
1787  * Topology list, bottom-up.
1788  */
1789 static struct sched_domain_topology_level default_topology[] = {
1790 #ifdef CONFIG_SCHED_SMT
1791 	SDTL_INIT(tl_smt_mask, cpu_smt_flags, SMT),
1792 #endif
1793 
1794 #ifdef CONFIG_SCHED_CLUSTER
1795 	SDTL_INIT(tl_cls_mask, cpu_cluster_flags, CLS),
1796 #endif
1797 
1798 #ifdef CONFIG_SCHED_MC
1799 	SDTL_INIT(tl_mc_mask, cpu_core_flags, MC),
1800 #endif
1801 	SDTL_INIT(tl_pkg_mask, NULL, PKG),
1802 	{ NULL, },
1803 };
1804 
1805 static struct sched_domain_topology_level *sched_domain_topology =
1806 	default_topology;
1807 static struct sched_domain_topology_level *sched_domain_topology_saved;
1808 
1809 #define for_each_sd_topology(tl)			\
1810 	for (tl = sched_domain_topology; tl->mask; tl++)
1811 
1812 void __init set_sched_topology(struct sched_domain_topology_level *tl)
1813 {
1814 	if (WARN_ON_ONCE(sched_smp_initialized))
1815 		return;
1816 
1817 	sched_domain_topology = tl;
1818 	sched_domain_topology_saved = NULL;
1819 }
1820 
1821 #ifdef CONFIG_NUMA
1822 static int cpu_numa_flags(void)
1823 {
1824 	return SD_NUMA;
1825 }
1826 
1827 static const struct cpumask *sd_numa_mask(struct sched_domain_topology_level *tl, int cpu)
1828 {
1829 	return sched_domains_numa_masks[tl->numa_level][cpu_to_node(cpu)];
1830 }
1831 
1832 static void sched_numa_warn(const char *str)
1833 {
1834 	static int done = false;
1835 	int i,j;
1836 
1837 	if (done)
1838 		return;
1839 
1840 	done = true;
1841 
1842 	printk(KERN_WARNING "ERROR: %s\n\n", str);
1843 
1844 	for (i = 0; i < nr_node_ids; i++) {
1845 		printk(KERN_WARNING "  ");
1846 		for (j = 0; j < nr_node_ids; j++) {
1847 			if (!node_state(i, N_CPU) || !node_state(j, N_CPU))
1848 				printk(KERN_CONT "(%02d) ", node_distance(i,j));
1849 			else
1850 				printk(KERN_CONT " %02d  ", node_distance(i,j));
1851 		}
1852 		printk(KERN_CONT "\n");
1853 	}
1854 	printk(KERN_WARNING "\n");
1855 }
1856 
1857 bool find_numa_distance(int distance)
1858 {
1859 	bool found = false;
1860 	int i, *distances;
1861 
1862 	if (distance == node_distance(0, 0))
1863 		return true;
1864 
1865 	rcu_read_lock();
1866 	distances = rcu_dereference(sched_numa_node_distance);
1867 	if (!distances)
1868 		goto unlock;
1869 	for (i = 0; i < sched_numa_node_levels; i++) {
1870 		if (distances[i] == distance) {
1871 			found = true;
1872 			break;
1873 		}
1874 	}
1875 unlock:
1876 	rcu_read_unlock();
1877 
1878 	return found;
1879 }
1880 
1881 #define for_each_cpu_node_but(n, nbut)		\
1882 	for_each_node_state(n, N_CPU)		\
1883 		if (n == nbut)			\
1884 			continue;		\
1885 		else
1886 
1887 /*
1888  * A system can have three types of NUMA topology:
1889  * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
1890  * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
1891  * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
1892  *
1893  * The difference between a glueless mesh topology and a backplane
1894  * topology lies in whether communication between not directly
1895  * connected nodes goes through intermediary nodes (where programs
1896  * could run), or through backplane controllers. This affects
1897  * placement of programs.
1898  *
1899  * The type of topology can be discerned with the following tests:
1900  * - If the maximum distance between any nodes is 1 hop, the system
1901  *   is directly connected.
1902  * - If for two nodes A and B, located N > 1 hops away from each other,
1903  *   there is an intermediary node C, which is < N hops away from both
1904  *   nodes A and B, the system is a glueless mesh.
1905  */
1906 static void init_numa_topology_type(int offline_node)
1907 {
1908 	int a, b, c, n;
1909 
1910 	n = sched_max_numa_distance;
1911 
1912 	if (sched_domains_numa_levels <= 2) {
1913 		sched_numa_topology_type = NUMA_DIRECT;
1914 		return;
1915 	}
1916 
1917 	for_each_cpu_node_but(a, offline_node) {
1918 		for_each_cpu_node_but(b, offline_node) {
1919 			/* Find two nodes furthest removed from each other. */
1920 			if (node_distance(a, b) < n)
1921 				continue;
1922 
1923 			/* Is there an intermediary node between a and b? */
1924 			for_each_cpu_node_but(c, offline_node) {
1925 				if (node_distance(a, c) < n &&
1926 				    node_distance(b, c) < n) {
1927 					sched_numa_topology_type =
1928 							NUMA_GLUELESS_MESH;
1929 					return;
1930 				}
1931 			}
1932 
1933 			sched_numa_topology_type = NUMA_BACKPLANE;
1934 			return;
1935 		}
1936 	}
1937 
1938 	pr_err("Failed to find a NUMA topology type, defaulting to DIRECT\n");
1939 	sched_numa_topology_type = NUMA_DIRECT;
1940 }
1941 
1942 
1943 #define NR_DISTANCE_VALUES (1 << DISTANCE_BITS)
1944 
1945 /*
1946  * An architecture could modify its NUMA distance, to change
1947  * grouping of NUMA nodes and number of NUMA levels when creating
1948  * NUMA level sched domains.
1949  *
1950  * A NUMA level is created for each unique
1951  * arch_sched_node_distance.
1952  */
1953 static int numa_node_dist(int i, int j)
1954 {
1955 	return node_distance(i, j);
1956 }
1957 
1958 int arch_sched_node_distance(int from, int to)
1959 			     __weak __alias(numa_node_dist);
1960 
1961 static bool modified_sched_node_distance(void)
1962 {
1963 	return numa_node_dist != arch_sched_node_distance;
1964 }
1965 
1966 static int sched_record_numa_dist(int offline_node, int (*n_dist)(int, int),
1967 				  int **dist, int *levels)
1968 {
1969 	unsigned long *distance_map __free(bitmap) = NULL;
1970 	int nr_levels = 0;
1971 	int i, j;
1972 	int *distances;
1973 
1974 	/*
1975 	 * O(nr_nodes^2) de-duplicating selection sort -- in order to find the
1976 	 * unique distances in the node_distance() table.
1977 	 */
1978 	distance_map = bitmap_alloc(NR_DISTANCE_VALUES, GFP_KERNEL);
1979 	if (!distance_map)
1980 		return -ENOMEM;
1981 
1982 	bitmap_zero(distance_map, NR_DISTANCE_VALUES);
1983 	for_each_cpu_node_but(i, offline_node) {
1984 		for_each_cpu_node_but(j, offline_node) {
1985 			int distance = n_dist(i, j);
1986 
1987 			if (distance < LOCAL_DISTANCE || distance >= NR_DISTANCE_VALUES) {
1988 				sched_numa_warn("Invalid distance value range");
1989 				return -EINVAL;
1990 			}
1991 
1992 			bitmap_set(distance_map, distance, 1);
1993 		}
1994 	}
1995 	/*
1996 	 * We can now figure out how many unique distance values there are and
1997 	 * allocate memory accordingly.
1998 	 */
1999 	nr_levels = bitmap_weight(distance_map, NR_DISTANCE_VALUES);
2000 
2001 	distances = kcalloc(nr_levels, sizeof(int), GFP_KERNEL);
2002 	if (!distances)
2003 		return -ENOMEM;
2004 
2005 	for (i = 0, j = 0; i < nr_levels; i++, j++) {
2006 		j = find_next_bit(distance_map, NR_DISTANCE_VALUES, j);
2007 		distances[i] = j;
2008 	}
2009 	*dist = distances;
2010 	*levels = nr_levels;
2011 
2012 	return 0;
2013 }
2014 
2015 void sched_init_numa(int offline_node)
2016 {
2017 	struct sched_domain_topology_level *tl;
2018 	int nr_levels, nr_node_levels;
2019 	int i, j;
2020 	int *distances, *domain_distances;
2021 	struct cpumask ***masks;
2022 
2023 	/* Record the NUMA distances from SLIT table */
2024 	if (sched_record_numa_dist(offline_node, numa_node_dist, &distances,
2025 				   &nr_node_levels))
2026 		return;
2027 
2028 	/* Record modified NUMA distances for building sched domains */
2029 	if (modified_sched_node_distance()) {
2030 		if (sched_record_numa_dist(offline_node, arch_sched_node_distance,
2031 					   &domain_distances, &nr_levels)) {
2032 			kfree(distances);
2033 			return;
2034 		}
2035 	} else {
2036 		domain_distances = distances;
2037 		nr_levels = nr_node_levels;
2038 	}
2039 	rcu_assign_pointer(sched_numa_node_distance, distances);
2040 	WRITE_ONCE(sched_max_numa_distance, distances[nr_node_levels - 1]);
2041 	WRITE_ONCE(sched_numa_node_levels, nr_node_levels);
2042 
2043 	/*
2044 	 * 'nr_levels' contains the number of unique distances
2045 	 *
2046 	 * The sched_domains_numa_distance[] array includes the actual distance
2047 	 * numbers.
2048 	 */
2049 
2050 	/*
2051 	 * Here, we should temporarily reset sched_domains_numa_levels to 0.
2052 	 * If it fails to allocate memory for array sched_domains_numa_masks[][],
2053 	 * the array will contain less then 'nr_levels' members. This could be
2054 	 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
2055 	 * in other functions.
2056 	 *
2057 	 * We reset it to 'nr_levels' at the end of this function.
2058 	 */
2059 	rcu_assign_pointer(sched_domains_numa_distance, domain_distances);
2060 
2061 	sched_domains_numa_levels = 0;
2062 
2063 	masks = kzalloc(sizeof(void *) * nr_levels, GFP_KERNEL);
2064 	if (!masks)
2065 		return;
2066 
2067 	/*
2068 	 * Now for each level, construct a mask per node which contains all
2069 	 * CPUs of nodes that are that many hops away from us.
2070 	 */
2071 	for (i = 0; i < nr_levels; i++) {
2072 		masks[i] = kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
2073 		if (!masks[i])
2074 			return;
2075 
2076 		for_each_cpu_node_but(j, offline_node) {
2077 			struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
2078 			int k;
2079 
2080 			if (!mask)
2081 				return;
2082 
2083 			masks[i][j] = mask;
2084 
2085 			for_each_cpu_node_but(k, offline_node) {
2086 				if (sched_debug() &&
2087 				    (arch_sched_node_distance(j, k) !=
2088 				     arch_sched_node_distance(k, j)))
2089 					sched_numa_warn("Node-distance not symmetric");
2090 
2091 				if (arch_sched_node_distance(j, k) >
2092 				    sched_domains_numa_distance[i])
2093 					continue;
2094 
2095 				cpumask_or(mask, mask, cpumask_of_node(k));
2096 			}
2097 		}
2098 	}
2099 	rcu_assign_pointer(sched_domains_numa_masks, masks);
2100 
2101 	/* Compute default topology size */
2102 	for (i = 0; sched_domain_topology[i].mask; i++);
2103 
2104 	tl = kzalloc((i + nr_levels + 1) *
2105 			sizeof(struct sched_domain_topology_level), GFP_KERNEL);
2106 	if (!tl)
2107 		return;
2108 
2109 	/*
2110 	 * Copy the default topology bits..
2111 	 */
2112 	for (i = 0; sched_domain_topology[i].mask; i++)
2113 		tl[i] = sched_domain_topology[i];
2114 
2115 	/*
2116 	 * Add the NUMA identity distance, aka single NODE.
2117 	 */
2118 	tl[i++] = SDTL_INIT(sd_numa_mask, NULL, NODE);
2119 
2120 	/*
2121 	 * .. and append 'j' levels of NUMA goodness.
2122 	 */
2123 	for (j = 1; j < nr_levels; i++, j++) {
2124 		tl[i] = SDTL_INIT(sd_numa_mask, cpu_numa_flags, NUMA);
2125 		tl[i].numa_level = j;
2126 	}
2127 
2128 	sched_domain_topology_saved = sched_domain_topology;
2129 	sched_domain_topology = tl;
2130 
2131 	sched_domains_numa_levels = nr_levels;
2132 
2133 	init_numa_topology_type(offline_node);
2134 }
2135 
2136 
2137 static void sched_reset_numa(void)
2138 {
2139 	int nr_levels, *distances, *dom_distances = NULL;
2140 	struct cpumask ***masks;
2141 
2142 	nr_levels = sched_domains_numa_levels;
2143 	sched_numa_node_levels = 0;
2144 	sched_domains_numa_levels = 0;
2145 	sched_max_numa_distance = 0;
2146 	sched_numa_topology_type = NUMA_DIRECT;
2147 	distances = sched_numa_node_distance;
2148 	if (sched_numa_node_distance != sched_domains_numa_distance)
2149 		dom_distances = sched_domains_numa_distance;
2150 	rcu_assign_pointer(sched_numa_node_distance, NULL);
2151 	rcu_assign_pointer(sched_domains_numa_distance, NULL);
2152 	masks = sched_domains_numa_masks;
2153 	rcu_assign_pointer(sched_domains_numa_masks, NULL);
2154 	if (distances || masks) {
2155 		int i, j;
2156 
2157 		synchronize_rcu();
2158 		kfree(distances);
2159 		kfree(dom_distances);
2160 		for (i = 0; i < nr_levels && masks; i++) {
2161 			if (!masks[i])
2162 				continue;
2163 			for_each_node(j)
2164 				kfree(masks[i][j]);
2165 			kfree(masks[i]);
2166 		}
2167 		kfree(masks);
2168 	}
2169 	if (sched_domain_topology_saved) {
2170 		kfree(sched_domain_topology);
2171 		sched_domain_topology = sched_domain_topology_saved;
2172 		sched_domain_topology_saved = NULL;
2173 	}
2174 }
2175 
2176 /*
2177  * Call with hotplug lock held
2178  */
2179 void sched_update_numa(int cpu, bool online)
2180 {
2181 	int node;
2182 
2183 	node = cpu_to_node(cpu);
2184 	/*
2185 	 * Scheduler NUMA topology is updated when the first CPU of a
2186 	 * node is onlined or the last CPU of a node is offlined.
2187 	 */
2188 	if (cpumask_weight(cpumask_of_node(node)) != 1)
2189 		return;
2190 
2191 	sched_reset_numa();
2192 	sched_init_numa(online ? NUMA_NO_NODE : node);
2193 }
2194 
2195 void sched_domains_numa_masks_set(unsigned int cpu)
2196 {
2197 	int node = cpu_to_node(cpu);
2198 	int i, j;
2199 
2200 	for (i = 0; i < sched_domains_numa_levels; i++) {
2201 		for (j = 0; j < nr_node_ids; j++) {
2202 			if (!node_state(j, N_CPU))
2203 				continue;
2204 
2205 			/* Set ourselves in the remote node's masks */
2206 			if (arch_sched_node_distance(j, node) <=
2207 			    sched_domains_numa_distance[i])
2208 				cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
2209 		}
2210 	}
2211 }
2212 
2213 void sched_domains_numa_masks_clear(unsigned int cpu)
2214 {
2215 	int i, j;
2216 
2217 	for (i = 0; i < sched_domains_numa_levels; i++) {
2218 		for (j = 0; j < nr_node_ids; j++) {
2219 			if (sched_domains_numa_masks[i][j])
2220 				cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
2221 		}
2222 	}
2223 }
2224 
2225 /*
2226  * sched_numa_find_closest() - given the NUMA topology, find the cpu
2227  *                             closest to @cpu from @cpumask.
2228  * cpumask: cpumask to find a cpu from
2229  * cpu: cpu to be close to
2230  *
2231  * returns: cpu, or nr_cpu_ids when nothing found.
2232  */
2233 int sched_numa_find_closest(const struct cpumask *cpus, int cpu)
2234 {
2235 	int i, j = cpu_to_node(cpu), found = nr_cpu_ids;
2236 	struct cpumask ***masks;
2237 
2238 	rcu_read_lock();
2239 	masks = rcu_dereference(sched_domains_numa_masks);
2240 	if (!masks)
2241 		goto unlock;
2242 	for (i = 0; i < sched_domains_numa_levels; i++) {
2243 		if (!masks[i][j])
2244 			break;
2245 		cpu = cpumask_any_and_distribute(cpus, masks[i][j]);
2246 		if (cpu < nr_cpu_ids) {
2247 			found = cpu;
2248 			break;
2249 		}
2250 	}
2251 unlock:
2252 	rcu_read_unlock();
2253 
2254 	return found;
2255 }
2256 
2257 struct __cmp_key {
2258 	const struct cpumask *cpus;
2259 	struct cpumask ***masks;
2260 	int node;
2261 	int cpu;
2262 	int w;
2263 };
2264 
2265 static int hop_cmp(const void *a, const void *b)
2266 {
2267 	struct cpumask **prev_hop, **cur_hop = *(struct cpumask ***)b;
2268 	struct __cmp_key *k = (struct __cmp_key *)a;
2269 
2270 	if (cpumask_weight_and(k->cpus, cur_hop[k->node]) <= k->cpu)
2271 		return 1;
2272 
2273 	if (b == k->masks) {
2274 		k->w = 0;
2275 		return 0;
2276 	}
2277 
2278 	prev_hop = *((struct cpumask ***)b - 1);
2279 	k->w = cpumask_weight_and(k->cpus, prev_hop[k->node]);
2280 	if (k->w <= k->cpu)
2281 		return 0;
2282 
2283 	return -1;
2284 }
2285 
2286 /**
2287  * sched_numa_find_nth_cpu() - given the NUMA topology, find the Nth closest CPU
2288  *                             from @cpus to @cpu, taking into account distance
2289  *                             from a given @node.
2290  * @cpus: cpumask to find a cpu from
2291  * @cpu: CPU to start searching
2292  * @node: NUMA node to order CPUs by distance
2293  *
2294  * Return: cpu, or nr_cpu_ids when nothing found.
2295  */
2296 int sched_numa_find_nth_cpu(const struct cpumask *cpus, int cpu, int node)
2297 {
2298 	struct __cmp_key k = { .cpus = cpus, .cpu = cpu };
2299 	struct cpumask ***hop_masks;
2300 	int hop, ret = nr_cpu_ids;
2301 
2302 	if (node == NUMA_NO_NODE)
2303 		return cpumask_nth_and(cpu, cpus, cpu_online_mask);
2304 
2305 	rcu_read_lock();
2306 
2307 	/* CPU-less node entries are uninitialized in sched_domains_numa_masks */
2308 	node = numa_nearest_node(node, N_CPU);
2309 	k.node = node;
2310 
2311 	k.masks = rcu_dereference(sched_domains_numa_masks);
2312 	if (!k.masks)
2313 		goto unlock;
2314 
2315 	hop_masks = bsearch(&k, k.masks, sched_domains_numa_levels, sizeof(k.masks[0]), hop_cmp);
2316 	if (!hop_masks)
2317 		goto unlock;
2318 	hop = hop_masks	- k.masks;
2319 
2320 	ret = hop ?
2321 		cpumask_nth_and_andnot(cpu - k.w, cpus, k.masks[hop][node], k.masks[hop-1][node]) :
2322 		cpumask_nth_and(cpu, cpus, k.masks[0][node]);
2323 unlock:
2324 	rcu_read_unlock();
2325 	return ret;
2326 }
2327 EXPORT_SYMBOL_GPL(sched_numa_find_nth_cpu);
2328 
2329 /**
2330  * sched_numa_hop_mask() - Get the cpumask of CPUs at most @hops hops away from
2331  *                         @node
2332  * @node: The node to count hops from.
2333  * @hops: Include CPUs up to that many hops away. 0 means local node.
2334  *
2335  * Return: On success, a pointer to a cpumask of CPUs at most @hops away from
2336  * @node, an error value otherwise.
2337  *
2338  * Requires rcu_lock to be held. Returned cpumask is only valid within that
2339  * read-side section, copy it if required beyond that.
2340  *
2341  * Note that not all hops are equal in distance; see sched_init_numa() for how
2342  * distances and masks are handled.
2343  * Also note that this is a reflection of sched_domains_numa_masks, which may change
2344  * during the lifetime of the system (offline nodes are taken out of the masks).
2345  */
2346 const struct cpumask *sched_numa_hop_mask(unsigned int node, unsigned int hops)
2347 {
2348 	struct cpumask ***masks;
2349 
2350 	if (node >= nr_node_ids || hops >= sched_domains_numa_levels)
2351 		return ERR_PTR(-EINVAL);
2352 
2353 	masks = rcu_dereference(sched_domains_numa_masks);
2354 	if (!masks)
2355 		return ERR_PTR(-EBUSY);
2356 
2357 	return masks[hops][node];
2358 }
2359 EXPORT_SYMBOL_GPL(sched_numa_hop_mask);
2360 
2361 #endif /* CONFIG_NUMA */
2362 
2363 static int __sdt_alloc(const struct cpumask *cpu_map)
2364 {
2365 	struct sched_domain_topology_level *tl;
2366 	int j;
2367 
2368 	for_each_sd_topology(tl) {
2369 		struct sd_data *sdd = &tl->data;
2370 
2371 		sdd->sd = alloc_percpu(struct sched_domain *);
2372 		if (!sdd->sd)
2373 			return -ENOMEM;
2374 
2375 		sdd->sds = alloc_percpu(struct sched_domain_shared *);
2376 		if (!sdd->sds)
2377 			return -ENOMEM;
2378 
2379 		sdd->sg = alloc_percpu(struct sched_group *);
2380 		if (!sdd->sg)
2381 			return -ENOMEM;
2382 
2383 		sdd->sgc = alloc_percpu(struct sched_group_capacity *);
2384 		if (!sdd->sgc)
2385 			return -ENOMEM;
2386 
2387 		for_each_cpu(j, cpu_map) {
2388 			struct sched_domain *sd;
2389 			struct sched_domain_shared *sds;
2390 			struct sched_group *sg;
2391 			struct sched_group_capacity *sgc;
2392 
2393 			sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
2394 					GFP_KERNEL, cpu_to_node(j));
2395 			if (!sd)
2396 				return -ENOMEM;
2397 
2398 			*per_cpu_ptr(sdd->sd, j) = sd;
2399 
2400 			sds = kzalloc_node(sizeof(struct sched_domain_shared),
2401 					GFP_KERNEL, cpu_to_node(j));
2402 			if (!sds)
2403 				return -ENOMEM;
2404 
2405 			*per_cpu_ptr(sdd->sds, j) = sds;
2406 
2407 			sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
2408 					GFP_KERNEL, cpu_to_node(j));
2409 			if (!sg)
2410 				return -ENOMEM;
2411 
2412 			sg->next = sg;
2413 
2414 			*per_cpu_ptr(sdd->sg, j) = sg;
2415 
2416 			sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
2417 					GFP_KERNEL, cpu_to_node(j));
2418 			if (!sgc)
2419 				return -ENOMEM;
2420 
2421 			sgc->id = j;
2422 
2423 			*per_cpu_ptr(sdd->sgc, j) = sgc;
2424 		}
2425 	}
2426 
2427 	return 0;
2428 }
2429 
2430 static void __sdt_free(const struct cpumask *cpu_map)
2431 {
2432 	struct sched_domain_topology_level *tl;
2433 	int j;
2434 
2435 	for_each_sd_topology(tl) {
2436 		struct sd_data *sdd = &tl->data;
2437 
2438 		for_each_cpu(j, cpu_map) {
2439 			struct sched_domain *sd;
2440 
2441 			if (sdd->sd) {
2442 				sd = *per_cpu_ptr(sdd->sd, j);
2443 				if (sd && (sd->flags & SD_NUMA))
2444 					free_sched_groups(sd->groups, 0);
2445 				kfree(*per_cpu_ptr(sdd->sd, j));
2446 			}
2447 
2448 			if (sdd->sds)
2449 				kfree(*per_cpu_ptr(sdd->sds, j));
2450 			if (sdd->sg)
2451 				kfree(*per_cpu_ptr(sdd->sg, j));
2452 			if (sdd->sgc)
2453 				kfree(*per_cpu_ptr(sdd->sgc, j));
2454 		}
2455 		free_percpu(sdd->sd);
2456 		sdd->sd = NULL;
2457 		free_percpu(sdd->sds);
2458 		sdd->sds = NULL;
2459 		free_percpu(sdd->sg);
2460 		sdd->sg = NULL;
2461 		free_percpu(sdd->sgc);
2462 		sdd->sgc = NULL;
2463 	}
2464 }
2465 
2466 static struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
2467 		const struct cpumask *cpu_map, struct sched_domain_attr *attr,
2468 		struct sched_domain *child, int cpu)
2469 {
2470 	struct sched_domain *sd = sd_init(tl, cpu_map, child, cpu);
2471 
2472 	if (child) {
2473 		sd->level = child->level + 1;
2474 		sched_domain_level_max = max(sched_domain_level_max, sd->level);
2475 		child->parent = sd;
2476 
2477 		if (!cpumask_subset(sched_domain_span(child),
2478 				    sched_domain_span(sd))) {
2479 			pr_err("BUG: arch topology borken\n");
2480 			pr_err("     the %s domain not a subset of the %s domain\n",
2481 					child->name, sd->name);
2482 			/* Fixup, ensure @sd has at least @child CPUs. */
2483 			cpumask_or(sched_domain_span(sd),
2484 				   sched_domain_span(sd),
2485 				   sched_domain_span(child));
2486 		}
2487 
2488 	}
2489 	set_domain_attribute(sd, attr);
2490 
2491 	return sd;
2492 }
2493 
2494 /*
2495  * Ensure topology masks are sane, i.e. there are no conflicts (overlaps) for
2496  * any two given CPUs on non-NUMA topology levels.
2497  */
2498 static bool topology_span_sane(const struct cpumask *cpu_map)
2499 {
2500 	struct sched_domain_topology_level *tl;
2501 	struct cpumask *covered, *id_seen;
2502 	int cpu;
2503 
2504 	lockdep_assert_held(&sched_domains_mutex);
2505 	covered = sched_domains_tmpmask;
2506 	id_seen = sched_domains_tmpmask2;
2507 
2508 	for_each_sd_topology(tl) {
2509 		int tl_common_flags = 0;
2510 
2511 		if (tl->sd_flags)
2512 			tl_common_flags = (*tl->sd_flags)();
2513 
2514 		/* NUMA levels are allowed to overlap */
2515 		if (tl_common_flags & SD_NUMA)
2516 			continue;
2517 
2518 		cpumask_clear(covered);
2519 		cpumask_clear(id_seen);
2520 
2521 		/*
2522 		 * Non-NUMA levels cannot partially overlap - they must be either
2523 		 * completely equal or completely disjoint. Otherwise we can end up
2524 		 * breaking the sched_group lists - i.e. a later get_group() pass
2525 		 * breaks the linking done for an earlier span.
2526 		 */
2527 		for_each_cpu(cpu, cpu_map) {
2528 			const struct cpumask *tl_cpu_mask = tl->mask(tl, cpu);
2529 			int id;
2530 
2531 			/* lowest bit set in this mask is used as a unique id */
2532 			id = cpumask_first(tl_cpu_mask);
2533 
2534 			if (cpumask_test_cpu(id, id_seen)) {
2535 				/* First CPU has already been seen, ensure identical spans */
2536 				if (!cpumask_equal(tl->mask(tl, id), tl_cpu_mask))
2537 					return false;
2538 			} else {
2539 				/* First CPU hasn't been seen before, ensure it's a completely new span */
2540 				if (cpumask_intersects(tl_cpu_mask, covered))
2541 					return false;
2542 
2543 				cpumask_or(covered, covered, tl_cpu_mask);
2544 				cpumask_set_cpu(id, id_seen);
2545 			}
2546 		}
2547 	}
2548 	return true;
2549 }
2550 
2551 /*
2552  * Build sched domains for a given set of CPUs and attach the sched domains
2553  * to the individual CPUs
2554  */
2555 static int
2556 build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr)
2557 {
2558 	enum s_alloc alloc_state = sa_none;
2559 	struct sched_domain *sd;
2560 	struct s_data d;
2561 	struct rq *rq = NULL;
2562 	int i, ret = -ENOMEM;
2563 	bool has_asym = false;
2564 	bool has_cluster = false;
2565 
2566 	if (WARN_ON(cpumask_empty(cpu_map)))
2567 		goto error;
2568 
2569 	alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
2570 	if (alloc_state != sa_rootdomain)
2571 		goto error;
2572 
2573 	/* Set up domains for CPUs specified by the cpu_map: */
2574 	for_each_cpu(i, cpu_map) {
2575 		struct sched_domain_topology_level *tl;
2576 
2577 		sd = NULL;
2578 		for_each_sd_topology(tl) {
2579 
2580 			sd = build_sched_domain(tl, cpu_map, attr, sd, i);
2581 
2582 			has_asym |= sd->flags & SD_ASYM_CPUCAPACITY;
2583 
2584 			if (tl == sched_domain_topology)
2585 				*per_cpu_ptr(d.sd, i) = sd;
2586 			if (cpumask_equal(cpu_map, sched_domain_span(sd)))
2587 				break;
2588 		}
2589 	}
2590 
2591 	if (WARN_ON(!topology_span_sane(cpu_map)))
2592 		goto error;
2593 
2594 	/* Build the groups for the domains */
2595 	for_each_cpu(i, cpu_map) {
2596 		for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
2597 			sd->span_weight = cpumask_weight(sched_domain_span(sd));
2598 			if (sd->flags & SD_NUMA) {
2599 				if (build_overlap_sched_groups(sd, i))
2600 					goto error;
2601 			} else {
2602 				if (build_sched_groups(sd, i))
2603 					goto error;
2604 			}
2605 		}
2606 	}
2607 
2608 	/*
2609 	 * Calculate an allowed NUMA imbalance such that LLCs do not get
2610 	 * imbalanced.
2611 	 */
2612 	for_each_cpu(i, cpu_map) {
2613 		unsigned int imb = 0;
2614 		unsigned int imb_span = 1;
2615 
2616 		for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
2617 			struct sched_domain *child = sd->child;
2618 
2619 			if (!(sd->flags & SD_SHARE_LLC) && child &&
2620 			    (child->flags & SD_SHARE_LLC)) {
2621 				struct sched_domain __rcu *top_p;
2622 				unsigned int nr_llcs;
2623 
2624 				/*
2625 				 * For a single LLC per node, allow an
2626 				 * imbalance up to 12.5% of the node. This is
2627 				 * arbitrary cutoff based two factors -- SMT and
2628 				 * memory channels. For SMT-2, the intent is to
2629 				 * avoid premature sharing of HT resources but
2630 				 * SMT-4 or SMT-8 *may* benefit from a different
2631 				 * cutoff. For memory channels, this is a very
2632 				 * rough estimate of how many channels may be
2633 				 * active and is based on recent CPUs with
2634 				 * many cores.
2635 				 *
2636 				 * For multiple LLCs, allow an imbalance
2637 				 * until multiple tasks would share an LLC
2638 				 * on one node while LLCs on another node
2639 				 * remain idle. This assumes that there are
2640 				 * enough logical CPUs per LLC to avoid SMT
2641 				 * factors and that there is a correlation
2642 				 * between LLCs and memory channels.
2643 				 */
2644 				nr_llcs = sd->span_weight / child->span_weight;
2645 				if (nr_llcs == 1)
2646 					imb = sd->span_weight >> 3;
2647 				else
2648 					imb = nr_llcs;
2649 				imb = max(1U, imb);
2650 				sd->imb_numa_nr = imb;
2651 
2652 				/* Set span based on the first NUMA domain. */
2653 				top_p = sd->parent;
2654 				while (top_p && !(top_p->flags & SD_NUMA)) {
2655 					top_p = top_p->parent;
2656 				}
2657 				imb_span = top_p ? top_p->span_weight : sd->span_weight;
2658 			} else {
2659 				int factor = max(1U, (sd->span_weight / imb_span));
2660 
2661 				sd->imb_numa_nr = imb * factor;
2662 			}
2663 		}
2664 	}
2665 
2666 	/* Calculate CPU capacity for physical packages and nodes */
2667 	for (i = nr_cpumask_bits-1; i >= 0; i--) {
2668 		if (!cpumask_test_cpu(i, cpu_map))
2669 			continue;
2670 
2671 		for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
2672 			claim_allocations(i, sd);
2673 			init_sched_groups_capacity(i, sd);
2674 		}
2675 	}
2676 
2677 	/* Attach the domains */
2678 	rcu_read_lock();
2679 	for_each_cpu(i, cpu_map) {
2680 		rq = cpu_rq(i);
2681 		sd = *per_cpu_ptr(d.sd, i);
2682 
2683 		cpu_attach_domain(sd, d.rd, i);
2684 
2685 		if (lowest_flag_domain(i, SD_CLUSTER))
2686 			has_cluster = true;
2687 	}
2688 	rcu_read_unlock();
2689 
2690 	if (has_asym)
2691 		static_branch_inc_cpuslocked(&sched_asym_cpucapacity);
2692 
2693 	if (has_cluster)
2694 		static_branch_inc_cpuslocked(&sched_cluster_active);
2695 
2696 	if (rq && sched_debug_verbose)
2697 		pr_info("root domain span: %*pbl\n", cpumask_pr_args(cpu_map));
2698 
2699 	ret = 0;
2700 error:
2701 	__free_domain_allocs(&d, alloc_state, cpu_map);
2702 
2703 	return ret;
2704 }
2705 
2706 /* Current sched domains: */
2707 static cpumask_var_t			*doms_cur;
2708 
2709 /* Number of sched domains in 'doms_cur': */
2710 static int				ndoms_cur;
2711 
2712 /* Attributes of custom domains in 'doms_cur' */
2713 static struct sched_domain_attr		*dattr_cur;
2714 
2715 /*
2716  * Special case: If a kmalloc() of a doms_cur partition (array of
2717  * cpumask) fails, then fallback to a single sched domain,
2718  * as determined by the single cpumask fallback_doms.
2719  */
2720 static cpumask_var_t			fallback_doms;
2721 
2722 /*
2723  * arch_update_cpu_topology lets virtualized architectures update the
2724  * CPU core maps. It is supposed to return 1 if the topology changed
2725  * or 0 if it stayed the same.
2726  */
2727 int __weak arch_update_cpu_topology(void)
2728 {
2729 	return 0;
2730 }
2731 
2732 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
2733 {
2734 	int i;
2735 	cpumask_var_t *doms;
2736 
2737 	doms = kmalloc_array(ndoms, sizeof(*doms), GFP_KERNEL);
2738 	if (!doms)
2739 		return NULL;
2740 	for (i = 0; i < ndoms; i++) {
2741 		if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
2742 			free_sched_domains(doms, i);
2743 			return NULL;
2744 		}
2745 	}
2746 	return doms;
2747 }
2748 
2749 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
2750 {
2751 	unsigned int i;
2752 	for (i = 0; i < ndoms; i++)
2753 		free_cpumask_var(doms[i]);
2754 	kfree(doms);
2755 }
2756 
2757 /*
2758  * Set up scheduler domains and groups.  For now this just excludes isolated
2759  * CPUs, but could be used to exclude other special cases in the future.
2760  */
2761 int __init sched_init_domains(const struct cpumask *cpu_map)
2762 {
2763 	int err;
2764 
2765 	zalloc_cpumask_var(&sched_domains_tmpmask, GFP_KERNEL);
2766 	zalloc_cpumask_var(&sched_domains_tmpmask2, GFP_KERNEL);
2767 	zalloc_cpumask_var(&fallback_doms, GFP_KERNEL);
2768 
2769 	arch_update_cpu_topology();
2770 	asym_cpu_capacity_scan();
2771 	ndoms_cur = 1;
2772 	doms_cur = alloc_sched_domains(ndoms_cur);
2773 	if (!doms_cur)
2774 		doms_cur = &fallback_doms;
2775 	cpumask_and(doms_cur[0], cpu_map, housekeeping_cpumask(HK_TYPE_DOMAIN));
2776 	err = build_sched_domains(doms_cur[0], NULL);
2777 
2778 	return err;
2779 }
2780 
2781 /*
2782  * Detach sched domains from a group of CPUs specified in cpu_map
2783  * These CPUs will now be attached to the NULL domain
2784  */
2785 static void detach_destroy_domains(const struct cpumask *cpu_map)
2786 {
2787 	unsigned int cpu = cpumask_any(cpu_map);
2788 	int i;
2789 
2790 	if (rcu_access_pointer(per_cpu(sd_asym_cpucapacity, cpu)))
2791 		static_branch_dec_cpuslocked(&sched_asym_cpucapacity);
2792 
2793 	if (static_branch_unlikely(&sched_cluster_active))
2794 		static_branch_dec_cpuslocked(&sched_cluster_active);
2795 
2796 	rcu_read_lock();
2797 	for_each_cpu(i, cpu_map)
2798 		cpu_attach_domain(NULL, &def_root_domain, i);
2799 	rcu_read_unlock();
2800 }
2801 
2802 /* handle null as "default" */
2803 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
2804 			struct sched_domain_attr *new, int idx_new)
2805 {
2806 	struct sched_domain_attr tmp;
2807 
2808 	/* Fast path: */
2809 	if (!new && !cur)
2810 		return 1;
2811 
2812 	tmp = SD_ATTR_INIT;
2813 
2814 	return !memcmp(cur ? (cur + idx_cur) : &tmp,
2815 			new ? (new + idx_new) : &tmp,
2816 			sizeof(struct sched_domain_attr));
2817 }
2818 
2819 /*
2820  * Partition sched domains as specified by the 'ndoms_new'
2821  * cpumasks in the array doms_new[] of cpumasks. This compares
2822  * doms_new[] to the current sched domain partitioning, doms_cur[].
2823  * It destroys each deleted domain and builds each new domain.
2824  *
2825  * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
2826  * The masks don't intersect (don't overlap.) We should setup one
2827  * sched domain for each mask. CPUs not in any of the cpumasks will
2828  * not be load balanced. If the same cpumask appears both in the
2829  * current 'doms_cur' domains and in the new 'doms_new', we can leave
2830  * it as it is.
2831  *
2832  * The passed in 'doms_new' should be allocated using
2833  * alloc_sched_domains.  This routine takes ownership of it and will
2834  * free_sched_domains it when done with it. If the caller failed the
2835  * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
2836  * and partition_sched_domains() will fallback to the single partition
2837  * 'fallback_doms', it also forces the domains to be rebuilt.
2838  *
2839  * If doms_new == NULL it will be replaced with cpu_online_mask.
2840  * ndoms_new == 0 is a special case for destroying existing domains,
2841  * and it will not create the default domain.
2842  *
2843  * Call with hotplug lock and sched_domains_mutex held
2844  */
2845 static void partition_sched_domains_locked(int ndoms_new, cpumask_var_t doms_new[],
2846 				    struct sched_domain_attr *dattr_new)
2847 {
2848 	bool __maybe_unused has_eas = false;
2849 	int i, j, n;
2850 	int new_topology;
2851 
2852 	lockdep_assert_held(&sched_domains_mutex);
2853 
2854 	/* Let the architecture update CPU core mappings: */
2855 	new_topology = arch_update_cpu_topology();
2856 	/* Trigger rebuilding CPU capacity asymmetry data */
2857 	if (new_topology)
2858 		asym_cpu_capacity_scan();
2859 
2860 	if (!doms_new) {
2861 		WARN_ON_ONCE(dattr_new);
2862 		n = 0;
2863 		doms_new = alloc_sched_domains(1);
2864 		if (doms_new) {
2865 			n = 1;
2866 			cpumask_and(doms_new[0], cpu_active_mask,
2867 				    housekeeping_cpumask(HK_TYPE_DOMAIN));
2868 		}
2869 	} else {
2870 		n = ndoms_new;
2871 	}
2872 
2873 	/* Destroy deleted domains: */
2874 	for (i = 0; i < ndoms_cur; i++) {
2875 		for (j = 0; j < n && !new_topology; j++) {
2876 			if (cpumask_equal(doms_cur[i], doms_new[j]) &&
2877 			    dattrs_equal(dattr_cur, i, dattr_new, j))
2878 				goto match1;
2879 		}
2880 		/* No match - a current sched domain not in new doms_new[] */
2881 		detach_destroy_domains(doms_cur[i]);
2882 match1:
2883 		;
2884 	}
2885 
2886 	n = ndoms_cur;
2887 	if (!doms_new) {
2888 		n = 0;
2889 		doms_new = &fallback_doms;
2890 		cpumask_and(doms_new[0], cpu_active_mask,
2891 			    housekeeping_cpumask(HK_TYPE_DOMAIN));
2892 	}
2893 
2894 	/* Build new domains: */
2895 	for (i = 0; i < ndoms_new; i++) {
2896 		for (j = 0; j < n && !new_topology; j++) {
2897 			if (cpumask_equal(doms_new[i], doms_cur[j]) &&
2898 			    dattrs_equal(dattr_new, i, dattr_cur, j))
2899 				goto match2;
2900 		}
2901 		/* No match - add a new doms_new */
2902 		build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
2903 match2:
2904 		;
2905 	}
2906 
2907 #if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL)
2908 	/* Build perf domains: */
2909 	for (i = 0; i < ndoms_new; i++) {
2910 		for (j = 0; j < n && !sched_energy_update; j++) {
2911 			if (cpumask_equal(doms_new[i], doms_cur[j]) &&
2912 			    cpu_rq(cpumask_first(doms_cur[j]))->rd->pd) {
2913 				has_eas = true;
2914 				goto match3;
2915 			}
2916 		}
2917 		/* No match - add perf domains for a new rd */
2918 		has_eas |= build_perf_domains(doms_new[i]);
2919 match3:
2920 		;
2921 	}
2922 	sched_energy_set(has_eas);
2923 #endif
2924 
2925 	/* Remember the new sched domains: */
2926 	if (doms_cur != &fallback_doms)
2927 		free_sched_domains(doms_cur, ndoms_cur);
2928 
2929 	kfree(dattr_cur);
2930 	doms_cur = doms_new;
2931 	dattr_cur = dattr_new;
2932 	ndoms_cur = ndoms_new;
2933 
2934 	update_sched_domain_debugfs();
2935 	dl_rebuild_rd_accounting();
2936 }
2937 
2938 /*
2939  * Call with hotplug lock held
2940  */
2941 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
2942 			     struct sched_domain_attr *dattr_new)
2943 {
2944 	sched_domains_mutex_lock();
2945 	partition_sched_domains_locked(ndoms_new, doms_new, dattr_new);
2946 	sched_domains_mutex_unlock();
2947 }
2948