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