x86/resctrl: Track the number of dirty RMID a CLOSID has
[linux-2.6-microblaze.git] / arch / x86 / kernel / cpu / resctrl / monitor.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Resource Director Technology(RDT)
4  * - Monitoring code
5  *
6  * Copyright (C) 2017 Intel Corporation
7  *
8  * Author:
9  *    Vikas Shivappa <vikas.shivappa@intel.com>
10  *
11  * This replaces the cqm.c based on perf but we reuse a lot of
12  * code and datastructures originally from Peter Zijlstra and Matt Fleming.
13  *
14  * More information about RDT be found in the Intel (R) x86 Architecture
15  * Software Developer Manual June 2016, volume 3, section 17.17.
16  */
17
18 #include <linux/module.h>
19 #include <linux/sizes.h>
20 #include <linux/slab.h>
21
22 #include <asm/cpu_device_id.h>
23 #include <asm/resctrl.h>
24
25 #include "internal.h"
26
27 /**
28  * struct rmid_entry - dirty tracking for all RMID.
29  * @closid:     The CLOSID for this entry.
30  * @rmid:       The RMID for this entry.
31  * @busy:       The number of domains with cached data using this RMID.
32  * @list:       Member of the rmid_free_lru list when busy == 0.
33  *
34  * Depending on the architecture the correct monitor is accessed using
35  * both @closid and @rmid, or @rmid only.
36  *
37  * Take the rdtgroup_mutex when accessing.
38  */
39 struct rmid_entry {
40         u32                             closid;
41         u32                             rmid;
42         int                             busy;
43         struct list_head                list;
44 };
45
46 /*
47  * @rmid_free_lru - A least recently used list of free RMIDs
48  *     These RMIDs are guaranteed to have an occupancy less than the
49  *     threshold occupancy
50  */
51 static LIST_HEAD(rmid_free_lru);
52
53 /*
54  * @closid_num_dirty_rmid    The number of dirty RMID each CLOSID has.
55  *     Only allocated when CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID is defined.
56  *     Indexed by CLOSID. Protected by rdtgroup_mutex.
57  */
58 static u32 *closid_num_dirty_rmid;
59
60 /*
61  * @rmid_limbo_count - count of currently unused but (potentially)
62  *     dirty RMIDs.
63  *     This counts RMIDs that no one is currently using but that
64  *     may have a occupancy value > resctrl_rmid_realloc_threshold. User can
65  *     change the threshold occupancy value.
66  */
67 static unsigned int rmid_limbo_count;
68
69 /*
70  * @rmid_entry - The entry in the limbo and free lists.
71  */
72 static struct rmid_entry        *rmid_ptrs;
73
74 /*
75  * Global boolean for rdt_monitor which is true if any
76  * resource monitoring is enabled.
77  */
78 bool rdt_mon_capable;
79
80 /*
81  * Global to indicate which monitoring events are enabled.
82  */
83 unsigned int rdt_mon_features;
84
85 /*
86  * This is the threshold cache occupancy in bytes at which we will consider an
87  * RMID available for re-allocation.
88  */
89 unsigned int resctrl_rmid_realloc_threshold;
90
91 /*
92  * This is the maximum value for the reallocation threshold, in bytes.
93  */
94 unsigned int resctrl_rmid_realloc_limit;
95
96 #define CF(cf)  ((unsigned long)(1048576 * (cf) + 0.5))
97
98 /*
99  * The correction factor table is documented in Documentation/arch/x86/resctrl.rst.
100  * If rmid > rmid threshold, MBM total and local values should be multiplied
101  * by the correction factor.
102  *
103  * The original table is modified for better code:
104  *
105  * 1. The threshold 0 is changed to rmid count - 1 so don't do correction
106  *    for the case.
107  * 2. MBM total and local correction table indexed by core counter which is
108  *    equal to (x86_cache_max_rmid + 1) / 8 - 1 and is from 0 up to 27.
109  * 3. The correction factor is normalized to 2^20 (1048576) so it's faster
110  *    to calculate corrected value by shifting:
111  *    corrected_value = (original_value * correction_factor) >> 20
112  */
113 static const struct mbm_correction_factor_table {
114         u32 rmidthreshold;
115         u64 cf;
116 } mbm_cf_table[] __initconst = {
117         {7,     CF(1.000000)},
118         {15,    CF(1.000000)},
119         {15,    CF(0.969650)},
120         {31,    CF(1.000000)},
121         {31,    CF(1.066667)},
122         {31,    CF(0.969650)},
123         {47,    CF(1.142857)},
124         {63,    CF(1.000000)},
125         {63,    CF(1.185115)},
126         {63,    CF(1.066553)},
127         {79,    CF(1.454545)},
128         {95,    CF(1.000000)},
129         {95,    CF(1.230769)},
130         {95,    CF(1.142857)},
131         {95,    CF(1.066667)},
132         {127,   CF(1.000000)},
133         {127,   CF(1.254863)},
134         {127,   CF(1.185255)},
135         {151,   CF(1.000000)},
136         {127,   CF(1.066667)},
137         {167,   CF(1.000000)},
138         {159,   CF(1.454334)},
139         {183,   CF(1.000000)},
140         {127,   CF(0.969744)},
141         {191,   CF(1.280246)},
142         {191,   CF(1.230921)},
143         {215,   CF(1.000000)},
144         {191,   CF(1.143118)},
145 };
146
147 static u32 mbm_cf_rmidthreshold __read_mostly = UINT_MAX;
148 static u64 mbm_cf __read_mostly;
149
150 static inline u64 get_corrected_mbm_count(u32 rmid, unsigned long val)
151 {
152         /* Correct MBM value. */
153         if (rmid > mbm_cf_rmidthreshold)
154                 val = (val * mbm_cf) >> 20;
155
156         return val;
157 }
158
159 /*
160  * x86 and arm64 differ in their handling of monitoring.
161  * x86's RMID are independent numbers, there is only one source of traffic
162  * with an RMID value of '1'.
163  * arm64's PMG extends the PARTID/CLOSID space, there are multiple sources of
164  * traffic with a PMG value of '1', one for each CLOSID, meaning the RMID
165  * value is no longer unique.
166  * To account for this, resctrl uses an index. On x86 this is just the RMID,
167  * on arm64 it encodes the CLOSID and RMID. This gives a unique number.
168  *
169  * The domain's rmid_busy_llc and rmid_ptrs[] are sized by index. The arch code
170  * must accept an attempt to read every index.
171  */
172 static inline struct rmid_entry *__rmid_entry(u32 idx)
173 {
174         struct rmid_entry *entry;
175         u32 closid, rmid;
176
177         entry = &rmid_ptrs[idx];
178         resctrl_arch_rmid_idx_decode(idx, &closid, &rmid);
179
180         WARN_ON_ONCE(entry->closid != closid);
181         WARN_ON_ONCE(entry->rmid != rmid);
182
183         return entry;
184 }
185
186 static int __rmid_read(u32 rmid, enum resctrl_event_id eventid, u64 *val)
187 {
188         u64 msr_val;
189
190         /*
191          * As per the SDM, when IA32_QM_EVTSEL.EvtID (bits 7:0) is configured
192          * with a valid event code for supported resource type and the bits
193          * IA32_QM_EVTSEL.RMID (bits 41:32) are configured with valid RMID,
194          * IA32_QM_CTR.data (bits 61:0) reports the monitored data.
195          * IA32_QM_CTR.Error (bit 63) and IA32_QM_CTR.Unavailable (bit 62)
196          * are error bits.
197          */
198         wrmsr(MSR_IA32_QM_EVTSEL, eventid, rmid);
199         rdmsrl(MSR_IA32_QM_CTR, msr_val);
200
201         if (msr_val & RMID_VAL_ERROR)
202                 return -EIO;
203         if (msr_val & RMID_VAL_UNAVAIL)
204                 return -EINVAL;
205
206         *val = msr_val;
207         return 0;
208 }
209
210 static struct arch_mbm_state *get_arch_mbm_state(struct rdt_hw_domain *hw_dom,
211                                                  u32 rmid,
212                                                  enum resctrl_event_id eventid)
213 {
214         switch (eventid) {
215         case QOS_L3_OCCUP_EVENT_ID:
216                 return NULL;
217         case QOS_L3_MBM_TOTAL_EVENT_ID:
218                 return &hw_dom->arch_mbm_total[rmid];
219         case QOS_L3_MBM_LOCAL_EVENT_ID:
220                 return &hw_dom->arch_mbm_local[rmid];
221         }
222
223         /* Never expect to get here */
224         WARN_ON_ONCE(1);
225
226         return NULL;
227 }
228
229 void resctrl_arch_reset_rmid(struct rdt_resource *r, struct rdt_domain *d,
230                              u32 unused, u32 rmid,
231                              enum resctrl_event_id eventid)
232 {
233         struct rdt_hw_domain *hw_dom = resctrl_to_arch_dom(d);
234         struct arch_mbm_state *am;
235
236         am = get_arch_mbm_state(hw_dom, rmid, eventid);
237         if (am) {
238                 memset(am, 0, sizeof(*am));
239
240                 /* Record any initial, non-zero count value. */
241                 __rmid_read(rmid, eventid, &am->prev_msr);
242         }
243 }
244
245 /*
246  * Assumes that hardware counters are also reset and thus that there is
247  * no need to record initial non-zero counts.
248  */
249 void resctrl_arch_reset_rmid_all(struct rdt_resource *r, struct rdt_domain *d)
250 {
251         struct rdt_hw_domain *hw_dom = resctrl_to_arch_dom(d);
252
253         if (is_mbm_total_enabled())
254                 memset(hw_dom->arch_mbm_total, 0,
255                        sizeof(*hw_dom->arch_mbm_total) * r->num_rmid);
256
257         if (is_mbm_local_enabled())
258                 memset(hw_dom->arch_mbm_local, 0,
259                        sizeof(*hw_dom->arch_mbm_local) * r->num_rmid);
260 }
261
262 static u64 mbm_overflow_count(u64 prev_msr, u64 cur_msr, unsigned int width)
263 {
264         u64 shift = 64 - width, chunks;
265
266         chunks = (cur_msr << shift) - (prev_msr << shift);
267         return chunks >> shift;
268 }
269
270 int resctrl_arch_rmid_read(struct rdt_resource *r, struct rdt_domain *d,
271                            u32 unused, u32 rmid, enum resctrl_event_id eventid,
272                            u64 *val)
273 {
274         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
275         struct rdt_hw_domain *hw_dom = resctrl_to_arch_dom(d);
276         struct arch_mbm_state *am;
277         u64 msr_val, chunks;
278         int ret;
279
280         if (!cpumask_test_cpu(smp_processor_id(), &d->cpu_mask))
281                 return -EINVAL;
282
283         ret = __rmid_read(rmid, eventid, &msr_val);
284         if (ret)
285                 return ret;
286
287         am = get_arch_mbm_state(hw_dom, rmid, eventid);
288         if (am) {
289                 am->chunks += mbm_overflow_count(am->prev_msr, msr_val,
290                                                  hw_res->mbm_width);
291                 chunks = get_corrected_mbm_count(rmid, am->chunks);
292                 am->prev_msr = msr_val;
293         } else {
294                 chunks = msr_val;
295         }
296
297         *val = chunks * hw_res->mon_scale;
298
299         return 0;
300 }
301
302 static void limbo_release_entry(struct rmid_entry *entry)
303 {
304         lockdep_assert_held(&rdtgroup_mutex);
305
306         rmid_limbo_count--;
307         list_add_tail(&entry->list, &rmid_free_lru);
308
309         if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID))
310                 closid_num_dirty_rmid[entry->closid]--;
311 }
312
313 /*
314  * Check the RMIDs that are marked as busy for this domain. If the
315  * reported LLC occupancy is below the threshold clear the busy bit and
316  * decrement the count. If the busy count gets to zero on an RMID, we
317  * free the RMID
318  */
319 void __check_limbo(struct rdt_domain *d, bool force_free)
320 {
321         struct rdt_resource *r = &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl;
322         u32 idx_limit = resctrl_arch_system_num_rmid_idx();
323         struct rmid_entry *entry;
324         u32 idx, cur_idx = 1;
325         bool rmid_dirty;
326         u64 val = 0;
327
328         /*
329          * Skip RMID 0 and start from RMID 1 and check all the RMIDs that
330          * are marked as busy for occupancy < threshold. If the occupancy
331          * is less than the threshold decrement the busy counter of the
332          * RMID and move it to the free list when the counter reaches 0.
333          */
334         for (;;) {
335                 idx = find_next_bit(d->rmid_busy_llc, idx_limit, cur_idx);
336                 if (idx >= idx_limit)
337                         break;
338
339                 entry = __rmid_entry(idx);
340                 if (resctrl_arch_rmid_read(r, d, entry->closid, entry->rmid,
341                                            QOS_L3_OCCUP_EVENT_ID, &val)) {
342                         rmid_dirty = true;
343                 } else {
344                         rmid_dirty = (val >= resctrl_rmid_realloc_threshold);
345                 }
346
347                 if (force_free || !rmid_dirty) {
348                         clear_bit(idx, d->rmid_busy_llc);
349                         if (!--entry->busy)
350                                 limbo_release_entry(entry);
351                 }
352                 cur_idx = idx + 1;
353         }
354 }
355
356 bool has_busy_rmid(struct rdt_domain *d)
357 {
358         u32 idx_limit = resctrl_arch_system_num_rmid_idx();
359
360         return find_first_bit(d->rmid_busy_llc, idx_limit) != idx_limit;
361 }
362
363 static struct rmid_entry *resctrl_find_free_rmid(u32 closid)
364 {
365         struct rmid_entry *itr;
366         u32 itr_idx, cmp_idx;
367
368         if (list_empty(&rmid_free_lru))
369                 return rmid_limbo_count ? ERR_PTR(-EBUSY) : ERR_PTR(-ENOSPC);
370
371         list_for_each_entry(itr, &rmid_free_lru, list) {
372                 /*
373                  * Get the index of this free RMID, and the index it would need
374                  * to be if it were used with this CLOSID.
375                  * If the CLOSID is irrelevant on this architecture, the two
376                  * index values are always the same on every entry and thus the
377                  * very first entry will be returned.
378                  */
379                 itr_idx = resctrl_arch_rmid_idx_encode(itr->closid, itr->rmid);
380                 cmp_idx = resctrl_arch_rmid_idx_encode(closid, itr->rmid);
381
382                 if (itr_idx == cmp_idx)
383                         return itr;
384         }
385
386         return ERR_PTR(-ENOSPC);
387 }
388
389 /*
390  * For MPAM the RMID value is not unique, and has to be considered with
391  * the CLOSID. The (CLOSID, RMID) pair is allocated on all domains, which
392  * allows all domains to be managed by a single free list.
393  * Each domain also has a rmid_busy_llc to reduce the work of the limbo handler.
394  */
395 int alloc_rmid(u32 closid)
396 {
397         struct rmid_entry *entry;
398
399         lockdep_assert_held(&rdtgroup_mutex);
400
401         entry = resctrl_find_free_rmid(closid);
402         if (IS_ERR(entry))
403                 return PTR_ERR(entry);
404
405         list_del(&entry->list);
406         return entry->rmid;
407 }
408
409 static void add_rmid_to_limbo(struct rmid_entry *entry)
410 {
411         struct rdt_resource *r = &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl;
412         struct rdt_domain *d;
413         int cpu, err;
414         u64 val = 0;
415         u32 idx;
416
417         lockdep_assert_held(&rdtgroup_mutex);
418
419         idx = resctrl_arch_rmid_idx_encode(entry->closid, entry->rmid);
420
421         entry->busy = 0;
422         cpu = get_cpu();
423         list_for_each_entry(d, &r->domains, list) {
424                 if (cpumask_test_cpu(cpu, &d->cpu_mask)) {
425                         err = resctrl_arch_rmid_read(r, d, entry->closid,
426                                                      entry->rmid,
427                                                      QOS_L3_OCCUP_EVENT_ID,
428                                                      &val);
429                         if (err || val <= resctrl_rmid_realloc_threshold)
430                                 continue;
431                 }
432
433                 /*
434                  * For the first limbo RMID in the domain,
435                  * setup up the limbo worker.
436                  */
437                 if (!has_busy_rmid(d))
438                         cqm_setup_limbo_handler(d, CQM_LIMBOCHECK_INTERVAL);
439                 set_bit(idx, d->rmid_busy_llc);
440                 entry->busy++;
441         }
442         put_cpu();
443
444         if (entry->busy) {
445                 rmid_limbo_count++;
446                 if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID))
447                         closid_num_dirty_rmid[entry->closid]++;
448         } else {
449                 list_add_tail(&entry->list, &rmid_free_lru);
450         }
451 }
452
453 void free_rmid(u32 closid, u32 rmid)
454 {
455         u32 idx = resctrl_arch_rmid_idx_encode(closid, rmid);
456         struct rmid_entry *entry;
457
458         lockdep_assert_held(&rdtgroup_mutex);
459
460         /*
461          * Do not allow the default rmid to be free'd. Comparing by index
462          * allows architectures that ignore the closid parameter to avoid an
463          * unnecessary check.
464          */
465         if (idx == resctrl_arch_rmid_idx_encode(RESCTRL_RESERVED_CLOSID,
466                                                 RESCTRL_RESERVED_RMID))
467                 return;
468
469         entry = __rmid_entry(idx);
470
471         if (is_llc_occupancy_enabled())
472                 add_rmid_to_limbo(entry);
473         else
474                 list_add_tail(&entry->list, &rmid_free_lru);
475 }
476
477 static struct mbm_state *get_mbm_state(struct rdt_domain *d, u32 closid,
478                                        u32 rmid, enum resctrl_event_id evtid)
479 {
480         u32 idx = resctrl_arch_rmid_idx_encode(closid, rmid);
481
482         switch (evtid) {
483         case QOS_L3_MBM_TOTAL_EVENT_ID:
484                 return &d->mbm_total[idx];
485         case QOS_L3_MBM_LOCAL_EVENT_ID:
486                 return &d->mbm_local[idx];
487         default:
488                 return NULL;
489         }
490 }
491
492 static int __mon_event_count(u32 closid, u32 rmid, struct rmid_read *rr)
493 {
494         struct mbm_state *m;
495         u64 tval = 0;
496
497         if (rr->first) {
498                 resctrl_arch_reset_rmid(rr->r, rr->d, closid, rmid, rr->evtid);
499                 m = get_mbm_state(rr->d, closid, rmid, rr->evtid);
500                 if (m)
501                         memset(m, 0, sizeof(struct mbm_state));
502                 return 0;
503         }
504
505         rr->err = resctrl_arch_rmid_read(rr->r, rr->d, closid, rmid, rr->evtid,
506                                          &tval);
507         if (rr->err)
508                 return rr->err;
509
510         rr->val += tval;
511
512         return 0;
513 }
514
515 /*
516  * mbm_bw_count() - Update bw count from values previously read by
517  *                  __mon_event_count().
518  * @closid:     The closid used to identify the cached mbm_state.
519  * @rmid:       The rmid used to identify the cached mbm_state.
520  * @rr:         The struct rmid_read populated by __mon_event_count().
521  *
522  * Supporting function to calculate the memory bandwidth
523  * and delta bandwidth in MBps. The chunks value previously read by
524  * __mon_event_count() is compared with the chunks value from the previous
525  * invocation. This must be called once per second to maintain values in MBps.
526  */
527 static void mbm_bw_count(u32 closid, u32 rmid, struct rmid_read *rr)
528 {
529         u32 idx = resctrl_arch_rmid_idx_encode(closid, rmid);
530         struct mbm_state *m = &rr->d->mbm_local[idx];
531         u64 cur_bw, bytes, cur_bytes;
532
533         cur_bytes = rr->val;
534         bytes = cur_bytes - m->prev_bw_bytes;
535         m->prev_bw_bytes = cur_bytes;
536
537         cur_bw = bytes / SZ_1M;
538
539         m->prev_bw = cur_bw;
540 }
541
542 /*
543  * This is called via IPI to read the CQM/MBM counters
544  * on a domain.
545  */
546 void mon_event_count(void *info)
547 {
548         struct rdtgroup *rdtgrp, *entry;
549         struct rmid_read *rr = info;
550         struct list_head *head;
551         int ret;
552
553         rdtgrp = rr->rgrp;
554
555         ret = __mon_event_count(rdtgrp->closid, rdtgrp->mon.rmid, rr);
556
557         /*
558          * For Ctrl groups read data from child monitor groups and
559          * add them together. Count events which are read successfully.
560          * Discard the rmid_read's reporting errors.
561          */
562         head = &rdtgrp->mon.crdtgrp_list;
563
564         if (rdtgrp->type == RDTCTRL_GROUP) {
565                 list_for_each_entry(entry, head, mon.crdtgrp_list) {
566                         if (__mon_event_count(entry->closid, entry->mon.rmid,
567                                               rr) == 0)
568                                 ret = 0;
569                 }
570         }
571
572         /*
573          * __mon_event_count() calls for newly created monitor groups may
574          * report -EINVAL/Unavailable if the monitor hasn't seen any traffic.
575          * Discard error if any of the monitor event reads succeeded.
576          */
577         if (ret == 0)
578                 rr->err = 0;
579 }
580
581 /*
582  * Feedback loop for MBA software controller (mba_sc)
583  *
584  * mba_sc is a feedback loop where we periodically read MBM counters and
585  * adjust the bandwidth percentage values via the IA32_MBA_THRTL_MSRs so
586  * that:
587  *
588  *   current bandwidth(cur_bw) < user specified bandwidth(user_bw)
589  *
590  * This uses the MBM counters to measure the bandwidth and MBA throttle
591  * MSRs to control the bandwidth for a particular rdtgrp. It builds on the
592  * fact that resctrl rdtgroups have both monitoring and control.
593  *
594  * The frequency of the checks is 1s and we just tag along the MBM overflow
595  * timer. Having 1s interval makes the calculation of bandwidth simpler.
596  *
597  * Although MBA's goal is to restrict the bandwidth to a maximum, there may
598  * be a need to increase the bandwidth to avoid unnecessarily restricting
599  * the L2 <-> L3 traffic.
600  *
601  * Since MBA controls the L2 external bandwidth where as MBM measures the
602  * L3 external bandwidth the following sequence could lead to such a
603  * situation.
604  *
605  * Consider an rdtgroup which had high L3 <-> memory traffic in initial
606  * phases -> mba_sc kicks in and reduced bandwidth percentage values -> but
607  * after some time rdtgroup has mostly L2 <-> L3 traffic.
608  *
609  * In this case we may restrict the rdtgroup's L2 <-> L3 traffic as its
610  * throttle MSRs already have low percentage values.  To avoid
611  * unnecessarily restricting such rdtgroups, we also increase the bandwidth.
612  */
613 static void update_mba_bw(struct rdtgroup *rgrp, struct rdt_domain *dom_mbm)
614 {
615         u32 closid, rmid, cur_msr_val, new_msr_val;
616         struct mbm_state *pmbm_data, *cmbm_data;
617         struct rdt_resource *r_mba;
618         struct rdt_domain *dom_mba;
619         u32 cur_bw, user_bw, idx;
620         struct list_head *head;
621         struct rdtgroup *entry;
622
623         if (!is_mbm_local_enabled())
624                 return;
625
626         r_mba = &rdt_resources_all[RDT_RESOURCE_MBA].r_resctrl;
627
628         closid = rgrp->closid;
629         rmid = rgrp->mon.rmid;
630         idx = resctrl_arch_rmid_idx_encode(closid, rmid);
631         pmbm_data = &dom_mbm->mbm_local[idx];
632
633         dom_mba = get_domain_from_cpu(smp_processor_id(), r_mba);
634         if (!dom_mba) {
635                 pr_warn_once("Failure to get domain for MBA update\n");
636                 return;
637         }
638
639         cur_bw = pmbm_data->prev_bw;
640         user_bw = dom_mba->mbps_val[closid];
641
642         /* MBA resource doesn't support CDP */
643         cur_msr_val = resctrl_arch_get_config(r_mba, dom_mba, closid, CDP_NONE);
644
645         /*
646          * For Ctrl groups read data from child monitor groups.
647          */
648         head = &rgrp->mon.crdtgrp_list;
649         list_for_each_entry(entry, head, mon.crdtgrp_list) {
650                 cmbm_data = &dom_mbm->mbm_local[entry->mon.rmid];
651                 cur_bw += cmbm_data->prev_bw;
652         }
653
654         /*
655          * Scale up/down the bandwidth linearly for the ctrl group.  The
656          * bandwidth step is the bandwidth granularity specified by the
657          * hardware.
658          * Always increase throttling if current bandwidth is above the
659          * target set by user.
660          * But avoid thrashing up and down on every poll by checking
661          * whether a decrease in throttling is likely to push the group
662          * back over target. E.g. if currently throttling to 30% of bandwidth
663          * on a system with 10% granularity steps, check whether moving to
664          * 40% would go past the limit by multiplying current bandwidth by
665          * "(30 + 10) / 30".
666          */
667         if (cur_msr_val > r_mba->membw.min_bw && user_bw < cur_bw) {
668                 new_msr_val = cur_msr_val - r_mba->membw.bw_gran;
669         } else if (cur_msr_val < MAX_MBA_BW &&
670                    (user_bw > (cur_bw * (cur_msr_val + r_mba->membw.min_bw) / cur_msr_val))) {
671                 new_msr_val = cur_msr_val + r_mba->membw.bw_gran;
672         } else {
673                 return;
674         }
675
676         resctrl_arch_update_one(r_mba, dom_mba, closid, CDP_NONE, new_msr_val);
677 }
678
679 static void mbm_update(struct rdt_resource *r, struct rdt_domain *d,
680                        u32 closid, u32 rmid)
681 {
682         struct rmid_read rr;
683
684         rr.first = false;
685         rr.r = r;
686         rr.d = d;
687
688         /*
689          * This is protected from concurrent reads from user
690          * as both the user and we hold the global mutex.
691          */
692         if (is_mbm_total_enabled()) {
693                 rr.evtid = QOS_L3_MBM_TOTAL_EVENT_ID;
694                 rr.val = 0;
695                 __mon_event_count(closid, rmid, &rr);
696         }
697         if (is_mbm_local_enabled()) {
698                 rr.evtid = QOS_L3_MBM_LOCAL_EVENT_ID;
699                 rr.val = 0;
700                 __mon_event_count(closid, rmid, &rr);
701
702                 /*
703                  * Call the MBA software controller only for the
704                  * control groups and when user has enabled
705                  * the software controller explicitly.
706                  */
707                 if (is_mba_sc(NULL))
708                         mbm_bw_count(closid, rmid, &rr);
709         }
710 }
711
712 /*
713  * Handler to scan the limbo list and move the RMIDs
714  * to free list whose occupancy < threshold_occupancy.
715  */
716 void cqm_handle_limbo(struct work_struct *work)
717 {
718         unsigned long delay = msecs_to_jiffies(CQM_LIMBOCHECK_INTERVAL);
719         int cpu = smp_processor_id();
720         struct rdt_domain *d;
721
722         mutex_lock(&rdtgroup_mutex);
723
724         d = container_of(work, struct rdt_domain, cqm_limbo.work);
725
726         __check_limbo(d, false);
727
728         if (has_busy_rmid(d))
729                 schedule_delayed_work_on(cpu, &d->cqm_limbo, delay);
730
731         mutex_unlock(&rdtgroup_mutex);
732 }
733
734 void cqm_setup_limbo_handler(struct rdt_domain *dom, unsigned long delay_ms)
735 {
736         unsigned long delay = msecs_to_jiffies(delay_ms);
737         int cpu;
738
739         cpu = cpumask_any(&dom->cpu_mask);
740         dom->cqm_work_cpu = cpu;
741
742         schedule_delayed_work_on(cpu, &dom->cqm_limbo, delay);
743 }
744
745 void mbm_handle_overflow(struct work_struct *work)
746 {
747         unsigned long delay = msecs_to_jiffies(MBM_OVERFLOW_INTERVAL);
748         struct rdtgroup *prgrp, *crgrp;
749         int cpu = smp_processor_id();
750         struct list_head *head;
751         struct rdt_resource *r;
752         struct rdt_domain *d;
753
754         mutex_lock(&rdtgroup_mutex);
755
756         if (!static_branch_likely(&rdt_mon_enable_key))
757                 goto out_unlock;
758
759         r = &rdt_resources_all[RDT_RESOURCE_L3].r_resctrl;
760         d = container_of(work, struct rdt_domain, mbm_over.work);
761
762         list_for_each_entry(prgrp, &rdt_all_groups, rdtgroup_list) {
763                 mbm_update(r, d, prgrp->closid, prgrp->mon.rmid);
764
765                 head = &prgrp->mon.crdtgrp_list;
766                 list_for_each_entry(crgrp, head, mon.crdtgrp_list)
767                         mbm_update(r, d, crgrp->closid, crgrp->mon.rmid);
768
769                 if (is_mba_sc(NULL))
770                         update_mba_bw(prgrp, d);
771         }
772
773         schedule_delayed_work_on(cpu, &d->mbm_over, delay);
774
775 out_unlock:
776         mutex_unlock(&rdtgroup_mutex);
777 }
778
779 void mbm_setup_overflow_handler(struct rdt_domain *dom, unsigned long delay_ms)
780 {
781         unsigned long delay = msecs_to_jiffies(delay_ms);
782         int cpu;
783
784         if (!static_branch_likely(&rdt_mon_enable_key))
785                 return;
786         cpu = cpumask_any(&dom->cpu_mask);
787         dom->mbm_work_cpu = cpu;
788         schedule_delayed_work_on(cpu, &dom->mbm_over, delay);
789 }
790
791 static int dom_data_init(struct rdt_resource *r)
792 {
793         u32 idx_limit = resctrl_arch_system_num_rmid_idx();
794         u32 num_closid = resctrl_arch_get_num_closid(r);
795         struct rmid_entry *entry = NULL;
796         int err = 0, i;
797         u32 idx;
798
799         mutex_lock(&rdtgroup_mutex);
800         if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID)) {
801                 u32 *tmp;
802
803                 /*
804                  * If the architecture hasn't provided a sanitised value here,
805                  * this may result in larger arrays than necessary. Resctrl will
806                  * use a smaller system wide value based on the resources in
807                  * use.
808                  */
809                 tmp = kcalloc(num_closid, sizeof(*tmp), GFP_KERNEL);
810                 if (!tmp) {
811                         err = -ENOMEM;
812                         goto out_unlock;
813                 }
814
815                 closid_num_dirty_rmid = tmp;
816         }
817
818         rmid_ptrs = kcalloc(idx_limit, sizeof(struct rmid_entry), GFP_KERNEL);
819         if (!rmid_ptrs) {
820                 if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID)) {
821                         kfree(closid_num_dirty_rmid);
822                         closid_num_dirty_rmid = NULL;
823                 }
824                 err = -ENOMEM;
825                 goto out_unlock;
826         }
827
828         for (i = 0; i < idx_limit; i++) {
829                 entry = &rmid_ptrs[i];
830                 INIT_LIST_HEAD(&entry->list);
831
832                 resctrl_arch_rmid_idx_decode(i, &entry->closid, &entry->rmid);
833                 list_add_tail(&entry->list, &rmid_free_lru);
834         }
835
836         /*
837          * RESCTRL_RESERVED_CLOSID and RESCTRL_RESERVED_RMID are special and
838          * are always allocated. These are used for the rdtgroup_default
839          * control group, which will be setup later in rdtgroup_init().
840          */
841         idx = resctrl_arch_rmid_idx_encode(RESCTRL_RESERVED_CLOSID,
842                                            RESCTRL_RESERVED_RMID);
843         entry = __rmid_entry(idx);
844         list_del(&entry->list);
845
846 out_unlock:
847         mutex_unlock(&rdtgroup_mutex);
848
849         return err;
850 }
851
852 static void __exit dom_data_exit(void)
853 {
854         mutex_lock(&rdtgroup_mutex);
855
856         if (IS_ENABLED(CONFIG_RESCTRL_RMID_DEPENDS_ON_CLOSID)) {
857                 kfree(closid_num_dirty_rmid);
858                 closid_num_dirty_rmid = NULL;
859         }
860
861         kfree(rmid_ptrs);
862         rmid_ptrs = NULL;
863
864         mutex_unlock(&rdtgroup_mutex);
865 }
866
867 static struct mon_evt llc_occupancy_event = {
868         .name           = "llc_occupancy",
869         .evtid          = QOS_L3_OCCUP_EVENT_ID,
870 };
871
872 static struct mon_evt mbm_total_event = {
873         .name           = "mbm_total_bytes",
874         .evtid          = QOS_L3_MBM_TOTAL_EVENT_ID,
875 };
876
877 static struct mon_evt mbm_local_event = {
878         .name           = "mbm_local_bytes",
879         .evtid          = QOS_L3_MBM_LOCAL_EVENT_ID,
880 };
881
882 /*
883  * Initialize the event list for the resource.
884  *
885  * Note that MBM events are also part of RDT_RESOURCE_L3 resource
886  * because as per the SDM the total and local memory bandwidth
887  * are enumerated as part of L3 monitoring.
888  */
889 static void l3_mon_evt_init(struct rdt_resource *r)
890 {
891         INIT_LIST_HEAD(&r->evt_list);
892
893         if (is_llc_occupancy_enabled())
894                 list_add_tail(&llc_occupancy_event.list, &r->evt_list);
895         if (is_mbm_total_enabled())
896                 list_add_tail(&mbm_total_event.list, &r->evt_list);
897         if (is_mbm_local_enabled())
898                 list_add_tail(&mbm_local_event.list, &r->evt_list);
899 }
900
901 int __init rdt_get_mon_l3_config(struct rdt_resource *r)
902 {
903         unsigned int mbm_offset = boot_cpu_data.x86_cache_mbm_width_offset;
904         struct rdt_hw_resource *hw_res = resctrl_to_arch_res(r);
905         unsigned int threshold;
906         int ret;
907
908         resctrl_rmid_realloc_limit = boot_cpu_data.x86_cache_size * 1024;
909         hw_res->mon_scale = boot_cpu_data.x86_cache_occ_scale;
910         r->num_rmid = boot_cpu_data.x86_cache_max_rmid + 1;
911         hw_res->mbm_width = MBM_CNTR_WIDTH_BASE;
912
913         if (mbm_offset > 0 && mbm_offset <= MBM_CNTR_WIDTH_OFFSET_MAX)
914                 hw_res->mbm_width += mbm_offset;
915         else if (mbm_offset > MBM_CNTR_WIDTH_OFFSET_MAX)
916                 pr_warn("Ignoring impossible MBM counter offset\n");
917
918         /*
919          * A reasonable upper limit on the max threshold is the number
920          * of lines tagged per RMID if all RMIDs have the same number of
921          * lines tagged in the LLC.
922          *
923          * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
924          */
925         threshold = resctrl_rmid_realloc_limit / r->num_rmid;
926
927         /*
928          * Because num_rmid may not be a power of two, round the value
929          * to the nearest multiple of hw_res->mon_scale so it matches a
930          * value the hardware will measure. mon_scale may not be a power of 2.
931          */
932         resctrl_rmid_realloc_threshold = resctrl_arch_round_mon_val(threshold);
933
934         ret = dom_data_init(r);
935         if (ret)
936                 return ret;
937
938         if (rdt_cpu_has(X86_FEATURE_BMEC)) {
939                 u32 eax, ebx, ecx, edx;
940
941                 /* Detect list of bandwidth sources that can be tracked */
942                 cpuid_count(0x80000020, 3, &eax, &ebx, &ecx, &edx);
943                 hw_res->mbm_cfg_mask = ecx & MAX_EVT_CONFIG_BITS;
944
945                 if (rdt_cpu_has(X86_FEATURE_CQM_MBM_TOTAL)) {
946                         mbm_total_event.configurable = true;
947                         mbm_config_rftype_init("mbm_total_bytes_config");
948                 }
949                 if (rdt_cpu_has(X86_FEATURE_CQM_MBM_LOCAL)) {
950                         mbm_local_event.configurable = true;
951                         mbm_config_rftype_init("mbm_local_bytes_config");
952                 }
953         }
954
955         l3_mon_evt_init(r);
956
957         r->mon_capable = true;
958
959         return 0;
960 }
961
962 void __exit rdt_put_mon_l3_config(void)
963 {
964         dom_data_exit();
965 }
966
967 void __init intel_rdt_mbm_apply_quirk(void)
968 {
969         int cf_index;
970
971         cf_index = (boot_cpu_data.x86_cache_max_rmid + 1) / 8 - 1;
972         if (cf_index >= ARRAY_SIZE(mbm_cf_table)) {
973                 pr_info("No MBM correction factor available\n");
974                 return;
975         }
976
977         mbm_cf_rmidthreshold = mbm_cf_table[cf_index].rmidthreshold;
978         mbm_cf = mbm_cf_table[cf_index].cf;
979 }