x86/resctrl: Calculate the index from the configuration type
[linux-2.6-microblaze.git] / arch / x86 / kernel / cpu / resctrl / core.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Resource Director Technology(RDT)
4  * - Cache Allocation code.
5  *
6  * Copyright (C) 2016 Intel Corporation
7  *
8  * Authors:
9  *    Fenghua Yu <fenghua.yu@intel.com>
10  *    Tony Luck <tony.luck@intel.com>
11  *    Vikas Shivappa <vikas.shivappa@intel.com>
12  *
13  * More information about RDT be found in the Intel (R) x86 Architecture
14  * Software Developer Manual June 2016, volume 3, section 17.17.
15  */
16
17 #define pr_fmt(fmt)     "resctrl: " fmt
18
19 #include <linux/slab.h>
20 #include <linux/err.h>
21 #include <linux/cacheinfo.h>
22 #include <linux/cpuhotplug.h>
23
24 #include <asm/intel-family.h>
25 #include <asm/resctrl.h>
26 #include "internal.h"
27
28 /* Mutex to protect rdtgroup access. */
29 DEFINE_MUTEX(rdtgroup_mutex);
30
31 /*
32  * The cached resctrl_pqr_state is strictly per CPU and can never be
33  * updated from a remote CPU. Functions which modify the state
34  * are called with interrupts disabled and no preemption, which
35  * is sufficient for the protection.
36  */
37 DEFINE_PER_CPU(struct resctrl_pqr_state, pqr_state);
38
39 /*
40  * Used to store the max resource name width and max resource data width
41  * to display the schemata in a tabular format
42  */
43 int max_name_width, max_data_width;
44
45 /*
46  * Global boolean for rdt_alloc which is true if any
47  * resource allocation is enabled.
48  */
49 bool rdt_alloc_capable;
50
51 static void
52 mba_wrmsr_intel(struct rdt_domain *d, struct msr_param *m,
53                 struct rdt_resource *r);
54 static void
55 cat_wrmsr(struct rdt_domain *d, struct msr_param *m, struct rdt_resource *r);
56 static void
57 mba_wrmsr_amd(struct rdt_domain *d, struct msr_param *m,
58               struct rdt_resource *r);
59
60 #define domain_init(id) LIST_HEAD_INIT(rdt_resources_all[id].r_resctrl.domains)
61
62 struct rdt_hw_resource rdt_resources_all[] = {
63         [RDT_RESOURCE_L3] =
64         {
65                 .conf_type                      = CDP_NONE,
66                 .r_resctrl = {
67                         .rid                    = RDT_RESOURCE_L3,
68                         .name                   = "L3",
69                         .cache_level            = 3,
70                         .cache = {
71                                 .min_cbm_bits   = 1,
72                         },
73                         .domains                = domain_init(RDT_RESOURCE_L3),
74                         .parse_ctrlval          = parse_cbm,
75                         .format_str             = "%d=%0*x",
76                         .fflags                 = RFTYPE_RES_CACHE,
77                 },
78                 .msr_base               = MSR_IA32_L3_CBM_BASE,
79                 .msr_update             = cat_wrmsr,
80         },
81         [RDT_RESOURCE_L3DATA] =
82         {
83                 .conf_type                      = CDP_DATA,
84                 .r_resctrl = {
85                         .rid                    = RDT_RESOURCE_L3DATA,
86                         .name                   = "L3DATA",
87                         .cache_level            = 3,
88                         .cache = {
89                                 .min_cbm_bits   = 1,
90                         },
91                         .domains                = domain_init(RDT_RESOURCE_L3DATA),
92                         .parse_ctrlval          = parse_cbm,
93                         .format_str             = "%d=%0*x",
94                         .fflags                 = RFTYPE_RES_CACHE,
95                 },
96                 .msr_base               = MSR_IA32_L3_CBM_BASE,
97                 .msr_update             = cat_wrmsr,
98         },
99         [RDT_RESOURCE_L3CODE] =
100         {
101                 .conf_type                      = CDP_CODE,
102                 .r_resctrl = {
103                         .rid                    = RDT_RESOURCE_L3CODE,
104                         .name                   = "L3CODE",
105                         .cache_level            = 3,
106                         .cache = {
107                                 .min_cbm_bits   = 1,
108                         },
109                         .domains                = domain_init(RDT_RESOURCE_L3CODE),
110                         .parse_ctrlval          = parse_cbm,
111                         .format_str             = "%d=%0*x",
112                         .fflags                 = RFTYPE_RES_CACHE,
113                 },
114                 .msr_base               = MSR_IA32_L3_CBM_BASE,
115                 .msr_update             = cat_wrmsr,
116         },
117         [RDT_RESOURCE_L2] =
118         {
119                 .conf_type                      = CDP_NONE,
120                 .r_resctrl = {
121                         .rid                    = RDT_RESOURCE_L2,
122                         .name                   = "L2",
123                         .cache_level            = 2,
124                         .cache = {
125                                 .min_cbm_bits   = 1,
126                         },
127                         .domains                = domain_init(RDT_RESOURCE_L2),
128                         .parse_ctrlval          = parse_cbm,
129                         .format_str             = "%d=%0*x",
130                         .fflags                 = RFTYPE_RES_CACHE,
131                 },
132                 .msr_base               = MSR_IA32_L2_CBM_BASE,
133                 .msr_update             = cat_wrmsr,
134         },
135         [RDT_RESOURCE_L2DATA] =
136         {
137                 .conf_type                      = CDP_DATA,
138                 .r_resctrl = {
139                         .rid                    = RDT_RESOURCE_L2DATA,
140                         .name                   = "L2DATA",
141                         .cache_level            = 2,
142                         .cache = {
143                                 .min_cbm_bits   = 1,
144                         },
145                         .domains                = domain_init(RDT_RESOURCE_L2DATA),
146                         .parse_ctrlval          = parse_cbm,
147                         .format_str             = "%d=%0*x",
148                         .fflags                 = RFTYPE_RES_CACHE,
149                 },
150                 .msr_base               = MSR_IA32_L2_CBM_BASE,
151                 .msr_update             = cat_wrmsr,
152         },
153         [RDT_RESOURCE_L2CODE] =
154         {
155                 .conf_type                      = CDP_CODE,
156                 .r_resctrl = {
157                         .rid                    = RDT_RESOURCE_L2CODE,
158                         .name                   = "L2CODE",
159                         .cache_level            = 2,
160                         .cache = {
161                                 .min_cbm_bits   = 1,
162                         },
163                         .domains                = domain_init(RDT_RESOURCE_L2CODE),
164                         .parse_ctrlval          = parse_cbm,
165                         .format_str             = "%d=%0*x",
166                         .fflags                 = RFTYPE_RES_CACHE,
167                 },
168                 .msr_base               = MSR_IA32_L2_CBM_BASE,
169                 .msr_update             = cat_wrmsr,
170         },
171         [RDT_RESOURCE_MBA] =
172         {
173                 .conf_type                      = CDP_NONE,
174                 .r_resctrl = {
175                         .rid                    = RDT_RESOURCE_MBA,
176                         .name                   = "MB",
177                         .cache_level            = 3,
178                         .domains                = domain_init(RDT_RESOURCE_MBA),
179                         .parse_ctrlval          = parse_bw,
180                         .format_str             = "%d=%*u",
181                         .fflags                 = RFTYPE_RES_MB,
182                 },
183         },
184 };
185
186 /*
187  * cache_alloc_hsw_probe() - Have to probe for Intel haswell server CPUs
188  * as they do not have CPUID enumeration support for Cache allocation.
189  * The check for Vendor/Family/Model is not enough to guarantee that
190  * the MSRs won't #GP fault because only the following SKUs support
191  * CAT:
192  *      Intel(R) Xeon(R)  CPU E5-2658  v3  @  2.20GHz
193  *      Intel(R) Xeon(R)  CPU E5-2648L v3  @  1.80GHz
194  *      Intel(R) Xeon(R)  CPU E5-2628L v3  @  2.00GHz
195  *      Intel(R) Xeon(R)  CPU E5-2618L v3  @  2.30GHz
196  *      Intel(R) Xeon(R)  CPU E5-2608L v3  @  2.00GHz
197  *      Intel(R) Xeon(R)  CPU E5-2658A v3  @  2.20GHz
198  *
199  * Probe by trying to write the first of the L3 cache mask registers
200  * and checking that the bits stick. Max CLOSids is always 4 and max cbm length
201  * is always 20 on hsw server parts. The minimum cache bitmask length
202  * allowed for HSW server is always 2 bits. Hardcode all of them.
203  */
204 static inline void cache_alloc_hsw_probe(void)
205 {
206         struct rdt_hw_resource *hw_res = &rdt_resources_all[RDT_RESOURCE_L3];
207         struct rdt_resource *r  = &hw_res->r_resctrl;
208         u32 l, h, max_cbm = BIT_MASK(20) - 1;
209
210         if (wrmsr_safe(MSR_IA32_L3_CBM_BASE, max_cbm, 0))
211                 return;
212
213         rdmsr(MSR_IA32_L3_CBM_BASE, l, h);
214
215         /* If all the bits were set in MSR, return success */
216         if (l != max_cbm)
217                 return;
218
219         hw_res->num_closid = 4;
220         r->default_ctrl = max_cbm;
221         r->cache.cbm_len = 20;
222         r->cache.shareable_bits = 0xc0000;
223         r->cache.min_cbm_bits = 2;
224         r->alloc_capable = true;
225         r->alloc_enabled = true;
226
227         rdt_alloc_capable = true;
228 }
229
230 bool is_mba_sc(struct rdt_resource *r)
231 {
232         if (!r)
233                 return rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl.membw.mba_sc;
234
235         return r->membw.mba_sc;
236 }
237
238 /*
239  * rdt_get_mb_table() - get a mapping of bandwidth(b/w) percentage values
240  * exposed to user interface and the h/w understandable delay values.
241  *
242  * The non-linear delay values have the granularity of power of two
243  * and also the h/w does not guarantee a curve for configured delay
244  * values vs. actual b/w enforced.
245  * Hence we need a mapping that is pre calibrated so the user can
246  * express the memory b/w as a percentage value.
247  */
248 static inline bool rdt_get_mb_table(struct rdt_resource *r)
249 {
250         /*
251          * There are no Intel SKUs as of now to support non-linear delay.
252          */
253         pr_info("MBA b/w map not implemented for cpu:%d, model:%d",
254                 boot_cpu_data.x86, boot_cpu_data.x86_model);
255
256         return false;
257 }
258
259 static bool __get_mem_config_intel(struct rdt_resource *r)
260 {
261         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
262         union cpuid_0x10_3_eax eax;
263         union cpuid_0x10_x_edx edx;
264         u32 ebx, ecx, max_delay;
265
266         cpuid_count(0x00000010, 3, &eax.full, &ebx, &ecx, &edx.full);
267         hw_res->num_closid = edx.split.cos_max + 1;
268         max_delay = eax.split.max_delay + 1;
269         r->default_ctrl = MAX_MBA_BW;
270         r->membw.arch_needs_linear = true;
271         if (ecx & MBA_IS_LINEAR) {
272                 r->membw.delay_linear = true;
273                 r->membw.min_bw = MAX_MBA_BW - max_delay;
274                 r->membw.bw_gran = MAX_MBA_BW - max_delay;
275         } else {
276                 if (!rdt_get_mb_table(r))
277                         return false;
278                 r->membw.arch_needs_linear = false;
279         }
280         r->data_width = 3;
281
282         if (boot_cpu_has(X86_FEATURE_PER_THREAD_MBA))
283                 r->membw.throttle_mode = THREAD_THROTTLE_PER_THREAD;
284         else
285                 r->membw.throttle_mode = THREAD_THROTTLE_MAX;
286         thread_throttle_mode_init();
287
288         r->alloc_capable = true;
289         r->alloc_enabled = true;
290
291         return true;
292 }
293
294 static bool __rdt_get_mem_config_amd(struct rdt_resource *r)
295 {
296         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
297         union cpuid_0x10_3_eax eax;
298         union cpuid_0x10_x_edx edx;
299         u32 ebx, ecx;
300
301         cpuid_count(0x80000020, 1, &eax.full, &ebx, &ecx, &edx.full);
302         hw_res->num_closid = edx.split.cos_max + 1;
303         r->default_ctrl = MAX_MBA_BW_AMD;
304
305         /* AMD does not use delay */
306         r->membw.delay_linear = false;
307         r->membw.arch_needs_linear = false;
308
309         /*
310          * AMD does not use memory delay throttle model to control
311          * the allocation like Intel does.
312          */
313         r->membw.throttle_mode = THREAD_THROTTLE_UNDEFINED;
314         r->membw.min_bw = 0;
315         r->membw.bw_gran = 1;
316         /* Max value is 2048, Data width should be 4 in decimal */
317         r->data_width = 4;
318
319         r->alloc_capable = true;
320         r->alloc_enabled = true;
321
322         return true;
323 }
324
325 static void rdt_get_cache_alloc_cfg(int idx, struct rdt_resource *r)
326 {
327         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
328         union cpuid_0x10_1_eax eax;
329         union cpuid_0x10_x_edx edx;
330         u32 ebx, ecx;
331
332         cpuid_count(0x00000010, idx, &eax.full, &ebx, &ecx, &edx.full);
333         hw_res->num_closid = edx.split.cos_max + 1;
334         r->cache.cbm_len = eax.split.cbm_len + 1;
335         r->default_ctrl = BIT_MASK(eax.split.cbm_len + 1) - 1;
336         r->cache.shareable_bits = ebx & r->default_ctrl;
337         r->data_width = (r->cache.cbm_len + 3) / 4;
338         r->alloc_capable = true;
339         r->alloc_enabled = true;
340 }
341
342 static void rdt_get_cdp_config(int level, int type)
343 {
344         struct rdt_resource *r_l = &rdt_resources_all[level].r_resctrl;
345         struct rdt_hw_resource *hw_res_l = resctrl_to_arch_res(r_l);
346         struct rdt_resource *r = &rdt_resources_all[type].r_resctrl;
347         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
348
349         hw_res->num_closid = hw_res_l->num_closid;
350         r->cache.cbm_len = r_l->cache.cbm_len;
351         r->default_ctrl = r_l->default_ctrl;
352         r->cache.shareable_bits = r_l->cache.shareable_bits;
353         r->data_width = (r->cache.cbm_len + 3) / 4;
354         r->alloc_capable = true;
355         /*
356          * By default, CDP is disabled. CDP can be enabled by mount parameter
357          * "cdp" during resctrl file system mount time.
358          */
359         r->alloc_enabled = false;
360         rdt_resources_all[level].cdp_enabled = false;
361         rdt_resources_all[type].cdp_enabled = false;
362         r_l->cdp_capable = true;
363         r->cdp_capable = true;
364 }
365
366 static void rdt_get_cdp_l3_config(void)
367 {
368         rdt_get_cdp_config(RDT_RESOURCE_L3, RDT_RESOURCE_L3DATA);
369         rdt_get_cdp_config(RDT_RESOURCE_L3, RDT_RESOURCE_L3CODE);
370 }
371
372 static void rdt_get_cdp_l2_config(void)
373 {
374         rdt_get_cdp_config(RDT_RESOURCE_L2, RDT_RESOURCE_L2DATA);
375         rdt_get_cdp_config(RDT_RESOURCE_L2, RDT_RESOURCE_L2CODE);
376 }
377
378 static void
379 mba_wrmsr_amd(struct rdt_domain *d, struct msr_param *m, struct rdt_resource *r)
380 {
381         unsigned int i;
382         struct rdt_hw_domain *hw_dom = resctrl_to_arch_dom(d);
383         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
384
385         for (i = m->low; i < m->high; i++)
386                 wrmsrl(hw_res->msr_base + i, hw_dom->ctrl_val[i]);
387 }
388
389 /*
390  * Map the memory b/w percentage value to delay values
391  * that can be written to QOS_MSRs.
392  * There are currently no SKUs which support non linear delay values.
393  */
394 u32 delay_bw_map(unsigned long bw, struct rdt_resource *r)
395 {
396         if (r->membw.delay_linear)
397                 return MAX_MBA_BW - bw;
398
399         pr_warn_once("Non Linear delay-bw map not supported but queried\n");
400         return r->default_ctrl;
401 }
402
403 static void
404 mba_wrmsr_intel(struct rdt_domain *d, struct msr_param *m,
405                 struct rdt_resource *r)
406 {
407         unsigned int i;
408         struct rdt_hw_domain *hw_dom = resctrl_to_arch_dom(d);
409         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
410
411         /*  Write the delay values for mba. */
412         for (i = m->low; i < m->high; i++)
413                 wrmsrl(hw_res->msr_base + i, delay_bw_map(hw_dom->ctrl_val[i], r));
414 }
415
416 static void
417 cat_wrmsr(struct rdt_domain *d, struct msr_param *m, struct rdt_resource *r)
418 {
419         unsigned int i;
420         struct rdt_hw_domain *hw_dom = resctrl_to_arch_dom(d);
421         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
422
423         for (i = m->low; i < m->high; i++)
424                 wrmsrl(hw_res->msr_base + i, hw_dom->ctrl_val[i]);
425 }
426
427 struct rdt_domain *get_domain_from_cpu(int cpu, struct rdt_resource *r)
428 {
429         struct rdt_domain *d;
430
431         list_for_each_entry(d, &r->domains, list) {
432                 /* Find the domain that contains this CPU */
433                 if (cpumask_test_cpu(cpu, &d->cpu_mask))
434                         return d;
435         }
436
437         return NULL;
438 }
439
440 u32 resctrl_arch_get_num_closid(struct rdt_resource *r)
441 {
442         return resctrl_to_arch_res(r)->num_closid;
443 }
444
445 void rdt_ctrl_update(void *arg)
446 {
447         struct msr_param *m = arg;
448         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(m->res);
449         struct rdt_resource *r = m->res;
450         int cpu = smp_processor_id();
451         struct rdt_domain *d;
452
453         d = get_domain_from_cpu(cpu, r);
454         if (d) {
455                 hw_res->msr_update(d, m, r);
456                 return;
457         }
458         pr_warn_once("cpu %d not found in any domain for resource %s\n",
459                      cpu, r->name);
460 }
461
462 /*
463  * rdt_find_domain - Find a domain in a resource that matches input resource id
464  *
465  * Search resource r's domain list to find the resource id. If the resource
466  * id is found in a domain, return the domain. Otherwise, if requested by
467  * caller, return the first domain whose id is bigger than the input id.
468  * The domain list is sorted by id in ascending order.
469  */
470 struct rdt_domain *rdt_find_domain(struct rdt_resource *r, int id,
471                                    struct list_head **pos)
472 {
473         struct rdt_domain *d;
474         struct list_head *l;
475
476         if (id < 0)
477                 return ERR_PTR(-ENODEV);
478
479         list_for_each(l, &r->domains) {
480                 d = list_entry(l, struct rdt_domain, list);
481                 /* When id is found, return its domain. */
482                 if (id == d->id)
483                         return d;
484                 /* Stop searching when finding id's position in sorted list. */
485                 if (id < d->id)
486                         break;
487         }
488
489         if (pos)
490                 *pos = l;
491
492         return NULL;
493 }
494
495 void setup_default_ctrlval(struct rdt_resource *r, u32 *dc, u32 *dm)
496 {
497         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
498         int i;
499
500         /*
501          * Initialize the Control MSRs to having no control.
502          * For Cache Allocation: Set all bits in cbm
503          * For Memory Allocation: Set b/w requested to 100%
504          * and the bandwidth in MBps to U32_MAX
505          */
506         for (i = 0; i < hw_res->num_closid; i++, dc++, dm++) {
507                 *dc = r->default_ctrl;
508                 *dm = MBA_MAX_MBPS;
509         }
510 }
511
512 static int domain_setup_ctrlval(struct rdt_resource *r, struct rdt_domain *d)
513 {
514         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
515         struct rdt_hw_domain *hw_dom = resctrl_to_arch_dom(d);
516         struct msr_param m;
517         u32 *dc, *dm;
518
519         dc = kmalloc_array(hw_res->num_closid, sizeof(*hw_dom->ctrl_val), GFP_KERNEL);
520         if (!dc)
521                 return -ENOMEM;
522
523         dm = kmalloc_array(hw_res->num_closid, sizeof(*hw_dom->mbps_val), GFP_KERNEL);
524         if (!dm) {
525                 kfree(dc);
526                 return -ENOMEM;
527         }
528
529         hw_dom->ctrl_val = dc;
530         hw_dom->mbps_val = dm;
531         setup_default_ctrlval(r, dc, dm);
532
533         m.low = 0;
534         m.high = hw_res->num_closid;
535         hw_res->msr_update(d, &m, r);
536         return 0;
537 }
538
539 static int domain_setup_mon_state(struct rdt_resource *r, struct rdt_domain *d)
540 {
541         size_t tsize;
542
543         if (is_llc_occupancy_enabled()) {
544                 d->rmid_busy_llc = bitmap_zalloc(r->num_rmid, GFP_KERNEL);
545                 if (!d->rmid_busy_llc)
546                         return -ENOMEM;
547                 INIT_DELAYED_WORK(&d->cqm_limbo, cqm_handle_limbo);
548         }
549         if (is_mbm_total_enabled()) {
550                 tsize = sizeof(*d->mbm_total);
551                 d->mbm_total = kcalloc(r->num_rmid, tsize, GFP_KERNEL);
552                 if (!d->mbm_total) {
553                         bitmap_free(d->rmid_busy_llc);
554                         return -ENOMEM;
555                 }
556         }
557         if (is_mbm_local_enabled()) {
558                 tsize = sizeof(*d->mbm_local);
559                 d->mbm_local = kcalloc(r->num_rmid, tsize, GFP_KERNEL);
560                 if (!d->mbm_local) {
561                         bitmap_free(d->rmid_busy_llc);
562                         kfree(d->mbm_total);
563                         return -ENOMEM;
564                 }
565         }
566
567         if (is_mbm_enabled()) {
568                 INIT_DELAYED_WORK(&d->mbm_over, mbm_handle_overflow);
569                 mbm_setup_overflow_handler(d, MBM_OVERFLOW_INTERVAL);
570         }
571
572         return 0;
573 }
574
575 /*
576  * domain_add_cpu - Add a cpu to a resource's domain list.
577  *
578  * If an existing domain in the resource r's domain list matches the cpu's
579  * resource id, add the cpu in the domain.
580  *
581  * Otherwise, a new domain is allocated and inserted into the right position
582  * in the domain list sorted by id in ascending order.
583  *
584  * The order in the domain list is visible to users when we print entries
585  * in the schemata file and schemata input is validated to have the same order
586  * as this list.
587  */
588 static void domain_add_cpu(int cpu, struct rdt_resource *r)
589 {
590         int id = get_cpu_cacheinfo_id(cpu, r->cache_level);
591         struct list_head *add_pos = NULL;
592         struct rdt_hw_domain *hw_dom;
593         struct rdt_domain *d;
594
595         d = rdt_find_domain(r, id, &add_pos);
596         if (IS_ERR(d)) {
597                 pr_warn("Couldn't find cache id for CPU %d\n", cpu);
598                 return;
599         }
600
601         if (d) {
602                 cpumask_set_cpu(cpu, &d->cpu_mask);
603                 if (r->cache.arch_has_per_cpu_cfg)
604                         rdt_domain_reconfigure_cdp(r);
605                 return;
606         }
607
608         hw_dom = kzalloc_node(sizeof(*hw_dom), GFP_KERNEL, cpu_to_node(cpu));
609         if (!hw_dom)
610                 return;
611
612         d = &hw_dom->d_resctrl;
613         d->id = id;
614         cpumask_set_cpu(cpu, &d->cpu_mask);
615
616         rdt_domain_reconfigure_cdp(r);
617
618         if (r->alloc_capable && domain_setup_ctrlval(r, d)) {
619                 kfree(d);
620                 return;
621         }
622
623         if (r->mon_capable && domain_setup_mon_state(r, d)) {
624                 kfree(d);
625                 return;
626         }
627
628         list_add_tail(&d->list, add_pos);
629
630         /*
631          * If resctrl is mounted, add
632          * per domain monitor data directories.
633          */
634         if (static_branch_unlikely(&rdt_mon_enable_key))
635                 mkdir_mondata_subdir_allrdtgrp(r, d);
636 }
637
638 static void domain_remove_cpu(int cpu, struct rdt_resource *r)
639 {
640         int id = get_cpu_cacheinfo_id(cpu, r->cache_level);
641         struct rdt_hw_domain *hw_dom;
642         struct rdt_domain *d;
643
644         d = rdt_find_domain(r, id, NULL);
645         if (IS_ERR_OR_NULL(d)) {
646                 pr_warn("Couldn't find cache id for CPU %d\n", cpu);
647                 return;
648         }
649         hw_dom = resctrl_to_arch_dom(d);
650
651         cpumask_clear_cpu(cpu, &d->cpu_mask);
652         if (cpumask_empty(&d->cpu_mask)) {
653                 /*
654                  * If resctrl is mounted, remove all the
655                  * per domain monitor data directories.
656                  */
657                 if (static_branch_unlikely(&rdt_mon_enable_key))
658                         rmdir_mondata_subdir_allrdtgrp(r, d->id);
659                 list_del(&d->list);
660                 if (r->mon_capable && is_mbm_enabled())
661                         cancel_delayed_work(&d->mbm_over);
662                 if (is_llc_occupancy_enabled() &&  has_busy_rmid(r, d)) {
663                         /*
664                          * When a package is going down, forcefully
665                          * decrement rmid->ebusy. There is no way to know
666                          * that the L3 was flushed and hence may lead to
667                          * incorrect counts in rare scenarios, but leaving
668                          * the RMID as busy creates RMID leaks if the
669                          * package never comes back.
670                          */
671                         __check_limbo(d, true);
672                         cancel_delayed_work(&d->cqm_limbo);
673                 }
674
675                 /*
676                  * rdt_domain "d" is going to be freed below, so clear
677                  * its pointer from pseudo_lock_region struct.
678                  */
679                 if (d->plr)
680                         d->plr->d = NULL;
681
682                 kfree(hw_dom->ctrl_val);
683                 kfree(hw_dom->mbps_val);
684                 bitmap_free(d->rmid_busy_llc);
685                 kfree(d->mbm_total);
686                 kfree(d->mbm_local);
687                 kfree(hw_dom);
688                 return;
689         }
690
691         if (r == &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl) {
692                 if (is_mbm_enabled() && cpu == d->mbm_work_cpu) {
693                         cancel_delayed_work(&d->mbm_over);
694                         mbm_setup_overflow_handler(d, 0);
695                 }
696                 if (is_llc_occupancy_enabled() && cpu == d->cqm_work_cpu &&
697                     has_busy_rmid(r, d)) {
698                         cancel_delayed_work(&d->cqm_limbo);
699                         cqm_setup_limbo_handler(d, 0);
700                 }
701         }
702 }
703
704 static void clear_closid_rmid(int cpu)
705 {
706         struct resctrl_pqr_state *state = this_cpu_ptr(&pqr_state);
707
708         state->default_closid = 0;
709         state->default_rmid = 0;
710         state->cur_closid = 0;
711         state->cur_rmid = 0;
712         wrmsr(IA32_PQR_ASSOC, 0, 0);
713 }
714
715 static int resctrl_online_cpu(unsigned int cpu)
716 {
717         struct rdt_resource *r;
718
719         mutex_lock(&rdtgroup_mutex);
720         for_each_capable_rdt_resource(r)
721                 domain_add_cpu(cpu, r);
722         /* The cpu is set in default rdtgroup after online. */
723         cpumask_set_cpu(cpu, &rdtgroup_default.cpu_mask);
724         clear_closid_rmid(cpu);
725         mutex_unlock(&rdtgroup_mutex);
726
727         return 0;
728 }
729
730 static void clear_childcpus(struct rdtgroup *r, unsigned int cpu)
731 {
732         struct rdtgroup *cr;
733
734         list_for_each_entry(cr, &r->mon.crdtgrp_list, mon.crdtgrp_list) {
735                 if (cpumask_test_and_clear_cpu(cpu, &cr->cpu_mask)) {
736                         break;
737                 }
738         }
739 }
740
741 static int resctrl_offline_cpu(unsigned int cpu)
742 {
743         struct rdtgroup *rdtgrp;
744         struct rdt_resource *r;
745
746         mutex_lock(&rdtgroup_mutex);
747         for_each_capable_rdt_resource(r)
748                 domain_remove_cpu(cpu, r);
749         list_for_each_entry(rdtgrp, &rdt_all_groups, rdtgroup_list) {
750                 if (cpumask_test_and_clear_cpu(cpu, &rdtgrp->cpu_mask)) {
751                         clear_childcpus(rdtgrp, cpu);
752                         break;
753                 }
754         }
755         clear_closid_rmid(cpu);
756         mutex_unlock(&rdtgroup_mutex);
757
758         return 0;
759 }
760
761 /*
762  * Choose a width for the resource name and resource data based on the
763  * resource that has widest name and cbm.
764  */
765 static __init void rdt_init_padding(void)
766 {
767         struct rdt_resource *r;
768
769         for_each_alloc_capable_rdt_resource(r) {
770                 if (r->data_width > max_data_width)
771                         max_data_width = r->data_width;
772         }
773 }
774
775 enum {
776         RDT_FLAG_CMT,
777         RDT_FLAG_MBM_TOTAL,
778         RDT_FLAG_MBM_LOCAL,
779         RDT_FLAG_L3_CAT,
780         RDT_FLAG_L3_CDP,
781         RDT_FLAG_L2_CAT,
782         RDT_FLAG_L2_CDP,
783         RDT_FLAG_MBA,
784 };
785
786 #define RDT_OPT(idx, n, f)      \
787 [idx] = {                       \
788         .name = n,              \
789         .flag = f               \
790 }
791
792 struct rdt_options {
793         char    *name;
794         int     flag;
795         bool    force_off, force_on;
796 };
797
798 static struct rdt_options rdt_options[]  __initdata = {
799         RDT_OPT(RDT_FLAG_CMT,       "cmt",      X86_FEATURE_CQM_OCCUP_LLC),
800         RDT_OPT(RDT_FLAG_MBM_TOTAL, "mbmtotal", X86_FEATURE_CQM_MBM_TOTAL),
801         RDT_OPT(RDT_FLAG_MBM_LOCAL, "mbmlocal", X86_FEATURE_CQM_MBM_LOCAL),
802         RDT_OPT(RDT_FLAG_L3_CAT,    "l3cat",    X86_FEATURE_CAT_L3),
803         RDT_OPT(RDT_FLAG_L3_CDP,    "l3cdp",    X86_FEATURE_CDP_L3),
804         RDT_OPT(RDT_FLAG_L2_CAT,    "l2cat",    X86_FEATURE_CAT_L2),
805         RDT_OPT(RDT_FLAG_L2_CDP,    "l2cdp",    X86_FEATURE_CDP_L2),
806         RDT_OPT(RDT_FLAG_MBA,       "mba",      X86_FEATURE_MBA),
807 };
808 #define NUM_RDT_OPTIONS ARRAY_SIZE(rdt_options)
809
810 static int __init set_rdt_options(char *str)
811 {
812         struct rdt_options *o;
813         bool force_off;
814         char *tok;
815
816         if (*str == '=')
817                 str++;
818         while ((tok = strsep(&str, ",")) != NULL) {
819                 force_off = *tok == '!';
820                 if (force_off)
821                         tok++;
822                 for (o = rdt_options; o < &rdt_options[NUM_RDT_OPTIONS]; o++) {
823                         if (strcmp(tok, o->name) == 0) {
824                                 if (force_off)
825                                         o->force_off = true;
826                                 else
827                                         o->force_on = true;
828                                 break;
829                         }
830                 }
831         }
832         return 1;
833 }
834 __setup("rdt", set_rdt_options);
835
836 static bool __init rdt_cpu_has(int flag)
837 {
838         bool ret = boot_cpu_has(flag);
839         struct rdt_options *o;
840
841         if (!ret)
842                 return ret;
843
844         for (o = rdt_options; o < &rdt_options[NUM_RDT_OPTIONS]; o++) {
845                 if (flag == o->flag) {
846                         if (o->force_off)
847                                 ret = false;
848                         if (o->force_on)
849                                 ret = true;
850                         break;
851                 }
852         }
853         return ret;
854 }
855
856 static __init bool get_mem_config(void)
857 {
858         struct rdt_hw_resource *hw_res = &rdt_resources_all[RDT_RESOURCE_MBA];
859
860         if (!rdt_cpu_has(X86_FEATURE_MBA))
861                 return false;
862
863         if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
864                 return __get_mem_config_intel(&hw_res->r_resctrl);
865         else if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
866                 return __rdt_get_mem_config_amd(&hw_res->r_resctrl);
867
868         return false;
869 }
870
871 static __init bool get_rdt_alloc_resources(void)
872 {
873         struct rdt_resource *r;
874         bool ret = false;
875
876         if (rdt_alloc_capable)
877                 return true;
878
879         if (!boot_cpu_has(X86_FEATURE_RDT_A))
880                 return false;
881
882         if (rdt_cpu_has(X86_FEATURE_CAT_L3)) {
883                 r = &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl;
884                 rdt_get_cache_alloc_cfg(1, r);
885                 if (rdt_cpu_has(X86_FEATURE_CDP_L3))
886                         rdt_get_cdp_l3_config();
887                 ret = true;
888         }
889         if (rdt_cpu_has(X86_FEATURE_CAT_L2)) {
890                 /* CPUID 0x10.2 fields are same format at 0x10.1 */
891                 r = &rdt_resources_all[RDT_RESOURCE_L2].r_resctrl;
892                 rdt_get_cache_alloc_cfg(2, r);
893                 if (rdt_cpu_has(X86_FEATURE_CDP_L2))
894                         rdt_get_cdp_l2_config();
895                 ret = true;
896         }
897
898         if (get_mem_config())
899                 ret = true;
900
901         return ret;
902 }
903
904 static __init bool get_rdt_mon_resources(void)
905 {
906         struct rdt_resource *r = &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl;
907
908         if (rdt_cpu_has(X86_FEATURE_CQM_OCCUP_LLC))
909                 rdt_mon_features |= (1 << QOS_L3_OCCUP_EVENT_ID);
910         if (rdt_cpu_has(X86_FEATURE_CQM_MBM_TOTAL))
911                 rdt_mon_features |= (1 << QOS_L3_MBM_TOTAL_EVENT_ID);
912         if (rdt_cpu_has(X86_FEATURE_CQM_MBM_LOCAL))
913                 rdt_mon_features |= (1 << QOS_L3_MBM_LOCAL_EVENT_ID);
914
915         if (!rdt_mon_features)
916                 return false;
917
918         return !rdt_get_mon_l3_config(r);
919 }
920
921 static __init void __check_quirks_intel(void)
922 {
923         switch (boot_cpu_data.x86_model) {
924         case INTEL_FAM6_HASWELL_X:
925                 if (!rdt_options[RDT_FLAG_L3_CAT].force_off)
926                         cache_alloc_hsw_probe();
927                 break;
928         case INTEL_FAM6_SKYLAKE_X:
929                 if (boot_cpu_data.x86_stepping <= 4)
930                         set_rdt_options("!cmt,!mbmtotal,!mbmlocal,!l3cat");
931                 else
932                         set_rdt_options("!l3cat");
933                 fallthrough;
934         case INTEL_FAM6_BROADWELL_X:
935                 intel_rdt_mbm_apply_quirk();
936                 break;
937         }
938 }
939
940 static __init void check_quirks(void)
941 {
942         if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
943                 __check_quirks_intel();
944 }
945
946 static __init bool get_rdt_resources(void)
947 {
948         rdt_alloc_capable = get_rdt_alloc_resources();
949         rdt_mon_capable = get_rdt_mon_resources();
950
951         return (rdt_mon_capable || rdt_alloc_capable);
952 }
953
954 static __init void rdt_init_res_defs_intel(void)
955 {
956         struct rdt_hw_resource *hw_res;
957         struct rdt_resource *r;
958
959         for_each_rdt_resource(r) {
960                 hw_res = resctrl_to_arch_res(r);
961
962                 if (r->rid == RDT_RESOURCE_L3 ||
963                     r->rid == RDT_RESOURCE_L3DATA ||
964                     r->rid == RDT_RESOURCE_L3CODE ||
965                     r->rid == RDT_RESOURCE_L2 ||
966                     r->rid == RDT_RESOURCE_L2DATA ||
967                     r->rid == RDT_RESOURCE_L2CODE) {
968                         r->cache.arch_has_sparse_bitmaps = false;
969                         r->cache.arch_has_empty_bitmaps = false;
970                         r->cache.arch_has_per_cpu_cfg = false;
971                 } else if (r->rid == RDT_RESOURCE_MBA) {
972                         hw_res->msr_base = MSR_IA32_MBA_THRTL_BASE;
973                         hw_res->msr_update = mba_wrmsr_intel;
974                 }
975         }
976 }
977
978 static __init void rdt_init_res_defs_amd(void)
979 {
980         struct rdt_hw_resource *hw_res;
981         struct rdt_resource *r;
982
983         for_each_rdt_resource(r) {
984                 hw_res = resctrl_to_arch_res(r);
985
986                 if (r->rid == RDT_RESOURCE_L3 ||
987                     r->rid == RDT_RESOURCE_L3DATA ||
988                     r->rid == RDT_RESOURCE_L3CODE ||
989                     r->rid == RDT_RESOURCE_L2 ||
990                     r->rid == RDT_RESOURCE_L2DATA ||
991                     r->rid == RDT_RESOURCE_L2CODE) {
992                         r->cache.arch_has_sparse_bitmaps = true;
993                         r->cache.arch_has_empty_bitmaps = true;
994                         r->cache.arch_has_per_cpu_cfg = true;
995                 } else if (r->rid == RDT_RESOURCE_MBA) {
996                         hw_res->msr_base = MSR_IA32_MBA_BW_BASE;
997                         hw_res->msr_update = mba_wrmsr_amd;
998                 }
999         }
1000 }
1001
1002 static __init void rdt_init_res_defs(void)
1003 {
1004         if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
1005                 rdt_init_res_defs_intel();
1006         else if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
1007                 rdt_init_res_defs_amd();
1008 }
1009
1010 static enum cpuhp_state rdt_online;
1011
1012 /* Runs once on the BSP during boot. */
1013 void resctrl_cpu_detect(struct cpuinfo_x86 *c)
1014 {
1015         if (!cpu_has(c, X86_FEATURE_CQM_LLC)) {
1016                 c->x86_cache_max_rmid  = -1;
1017                 c->x86_cache_occ_scale = -1;
1018                 c->x86_cache_mbm_width_offset = -1;
1019                 return;
1020         }
1021
1022         /* will be overridden if occupancy monitoring exists */
1023         c->x86_cache_max_rmid = cpuid_ebx(0xf);
1024
1025         if (cpu_has(c, X86_FEATURE_CQM_OCCUP_LLC) ||
1026             cpu_has(c, X86_FEATURE_CQM_MBM_TOTAL) ||
1027             cpu_has(c, X86_FEATURE_CQM_MBM_LOCAL)) {
1028                 u32 eax, ebx, ecx, edx;
1029
1030                 /* QoS sub-leaf, EAX=0Fh, ECX=1 */
1031                 cpuid_count(0xf, 1, &eax, &ebx, &ecx, &edx);
1032
1033                 c->x86_cache_max_rmid  = ecx;
1034                 c->x86_cache_occ_scale = ebx;
1035                 c->x86_cache_mbm_width_offset = eax & 0xff;
1036
1037                 if (c->x86_vendor == X86_VENDOR_AMD && !c->x86_cache_mbm_width_offset)
1038                         c->x86_cache_mbm_width_offset = MBM_CNTR_WIDTH_OFFSET_AMD;
1039         }
1040 }
1041
1042 static int __init resctrl_late_init(void)
1043 {
1044         struct rdt_resource *r;
1045         int state, ret;
1046
1047         /*
1048          * Initialize functions(or definitions) that are different
1049          * between vendors here.
1050          */
1051         rdt_init_res_defs();
1052
1053         check_quirks();
1054
1055         if (!get_rdt_resources())
1056                 return -ENODEV;
1057
1058         rdt_init_padding();
1059
1060         state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
1061                                   "x86/resctrl/cat:online:",
1062                                   resctrl_online_cpu, resctrl_offline_cpu);
1063         if (state < 0)
1064                 return state;
1065
1066         ret = rdtgroup_init();
1067         if (ret) {
1068                 cpuhp_remove_state(state);
1069                 return ret;
1070         }
1071         rdt_online = state;
1072
1073         for_each_alloc_capable_rdt_resource(r)
1074                 pr_info("%s allocation detected\n", r->name);
1075
1076         for_each_mon_capable_rdt_resource(r)
1077                 pr_info("%s monitoring detected\n", r->name);
1078
1079         return 0;
1080 }
1081
1082 late_initcall(resctrl_late_init);
1083
1084 static void __exit resctrl_exit(void)
1085 {
1086         cpuhp_remove_state(rdt_online);
1087         rdtgroup_exit();
1088 }
1089
1090 __exitcall(resctrl_exit);