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