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