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