perf/x86/mbm: Add Intel Memory B/W Monitoring enumeration and init
[linux-2.6-microblaze.git] / arch / x86 / events / intel / cqm.c
1 /*
2  * Intel Cache Quality-of-Service Monitoring (CQM) support.
3  *
4  * Based very, very heavily on work by Peter Zijlstra.
5  */
6
7 #include <linux/perf_event.h>
8 #include <linux/slab.h>
9 #include <asm/cpu_device_id.h>
10 #include "../perf_event.h"
11
12 #define MSR_IA32_PQR_ASSOC      0x0c8f
13 #define MSR_IA32_QM_CTR         0x0c8e
14 #define MSR_IA32_QM_EVTSEL      0x0c8d
15
16 static u32 cqm_max_rmid = -1;
17 static unsigned int cqm_l3_scale; /* supposedly cacheline size */
18 static bool cqm_enabled, mbm_enabled;
19
20 /**
21  * struct intel_pqr_state - State cache for the PQR MSR
22  * @rmid:               The cached Resource Monitoring ID
23  * @closid:             The cached Class Of Service ID
24  * @rmid_usecnt:        The usage counter for rmid
25  *
26  * The upper 32 bits of MSR_IA32_PQR_ASSOC contain closid and the
27  * lower 10 bits rmid. The update to MSR_IA32_PQR_ASSOC always
28  * contains both parts, so we need to cache them.
29  *
30  * The cache also helps to avoid pointless updates if the value does
31  * not change.
32  */
33 struct intel_pqr_state {
34         u32                     rmid;
35         u32                     closid;
36         int                     rmid_usecnt;
37 };
38
39 /*
40  * The cached intel_pqr_state is strictly per CPU and can never be
41  * updated from a remote CPU. Both functions which modify the state
42  * (intel_cqm_event_start and intel_cqm_event_stop) are called with
43  * interrupts disabled, which is sufficient for the protection.
44  */
45 static DEFINE_PER_CPU(struct intel_pqr_state, pqr_state);
46 /**
47  * struct sample - mbm event's (local or total) data
48  * @total_bytes    #bytes since we began monitoring
49  * @prev_msr       previous value of MSR
50  */
51 struct sample {
52         u64     total_bytes;
53         u64     prev_msr;
54 };
55
56 /*
57  * samples profiled for total memory bandwidth type events
58  */
59 static struct sample *mbm_total;
60 /*
61  * samples profiled for local memory bandwidth type events
62  */
63 static struct sample *mbm_local;
64
65 /*
66  * Protects cache_cgroups and cqm_rmid_free_lru and cqm_rmid_limbo_lru.
67  * Also protects event->hw.cqm_rmid
68  *
69  * Hold either for stability, both for modification of ->hw.cqm_rmid.
70  */
71 static DEFINE_MUTEX(cache_mutex);
72 static DEFINE_RAW_SPINLOCK(cache_lock);
73
74 /*
75  * Groups of events that have the same target(s), one RMID per group.
76  */
77 static LIST_HEAD(cache_groups);
78
79 /*
80  * Mask of CPUs for reading CQM values. We only need one per-socket.
81  */
82 static cpumask_t cqm_cpumask;
83
84 #define RMID_VAL_ERROR          (1ULL << 63)
85 #define RMID_VAL_UNAVAIL        (1ULL << 62)
86
87 #define QOS_L3_OCCUP_EVENT_ID   (1 << 0)
88
89 #define QOS_EVENT_MASK  QOS_L3_OCCUP_EVENT_ID
90
91 /*
92  * This is central to the rotation algorithm in __intel_cqm_rmid_rotate().
93  *
94  * This rmid is always free and is guaranteed to have an associated
95  * near-zero occupancy value, i.e. no cachelines are tagged with this
96  * RMID, once __intel_cqm_rmid_rotate() returns.
97  */
98 static u32 intel_cqm_rotation_rmid;
99
100 #define INVALID_RMID            (-1)
101
102 /*
103  * Is @rmid valid for programming the hardware?
104  *
105  * rmid 0 is reserved by the hardware for all non-monitored tasks, which
106  * means that we should never come across an rmid with that value.
107  * Likewise, an rmid value of -1 is used to indicate "no rmid currently
108  * assigned" and is used as part of the rotation code.
109  */
110 static inline bool __rmid_valid(u32 rmid)
111 {
112         if (!rmid || rmid == INVALID_RMID)
113                 return false;
114
115         return true;
116 }
117
118 static u64 __rmid_read(u32 rmid)
119 {
120         u64 val;
121
122         /*
123          * Ignore the SDM, this thing is _NOTHING_ like a regular perfcnt,
124          * it just says that to increase confusion.
125          */
126         wrmsr(MSR_IA32_QM_EVTSEL, QOS_L3_OCCUP_EVENT_ID, rmid);
127         rdmsrl(MSR_IA32_QM_CTR, val);
128
129         /*
130          * Aside from the ERROR and UNAVAIL bits, assume this thing returns
131          * the number of cachelines tagged with @rmid.
132          */
133         return val;
134 }
135
136 enum rmid_recycle_state {
137         RMID_YOUNG = 0,
138         RMID_AVAILABLE,
139         RMID_DIRTY,
140 };
141
142 struct cqm_rmid_entry {
143         u32 rmid;
144         enum rmid_recycle_state state;
145         struct list_head list;
146         unsigned long queue_time;
147 };
148
149 /*
150  * cqm_rmid_free_lru - A least recently used list of RMIDs.
151  *
152  * Oldest entry at the head, newest (most recently used) entry at the
153  * tail. This list is never traversed, it's only used to keep track of
154  * the lru order. That is, we only pick entries of the head or insert
155  * them on the tail.
156  *
157  * All entries on the list are 'free', and their RMIDs are not currently
158  * in use. To mark an RMID as in use, remove its entry from the lru
159  * list.
160  *
161  *
162  * cqm_rmid_limbo_lru - list of currently unused but (potentially) dirty RMIDs.
163  *
164  * This list is contains RMIDs that no one is currently using but that
165  * may have a non-zero occupancy value associated with them. The
166  * rotation worker moves RMIDs from the limbo list to the free list once
167  * the occupancy value drops below __intel_cqm_threshold.
168  *
169  * Both lists are protected by cache_mutex.
170  */
171 static LIST_HEAD(cqm_rmid_free_lru);
172 static LIST_HEAD(cqm_rmid_limbo_lru);
173
174 /*
175  * We use a simple array of pointers so that we can lookup a struct
176  * cqm_rmid_entry in O(1). This alleviates the callers of __get_rmid()
177  * and __put_rmid() from having to worry about dealing with struct
178  * cqm_rmid_entry - they just deal with rmids, i.e. integers.
179  *
180  * Once this array is initialized it is read-only. No locks are required
181  * to access it.
182  *
183  * All entries for all RMIDs can be looked up in the this array at all
184  * times.
185  */
186 static struct cqm_rmid_entry **cqm_rmid_ptrs;
187
188 static inline struct cqm_rmid_entry *__rmid_entry(u32 rmid)
189 {
190         struct cqm_rmid_entry *entry;
191
192         entry = cqm_rmid_ptrs[rmid];
193         WARN_ON(entry->rmid != rmid);
194
195         return entry;
196 }
197
198 /*
199  * Returns < 0 on fail.
200  *
201  * We expect to be called with cache_mutex held.
202  */
203 static u32 __get_rmid(void)
204 {
205         struct cqm_rmid_entry *entry;
206
207         lockdep_assert_held(&cache_mutex);
208
209         if (list_empty(&cqm_rmid_free_lru))
210                 return INVALID_RMID;
211
212         entry = list_first_entry(&cqm_rmid_free_lru, struct cqm_rmid_entry, list);
213         list_del(&entry->list);
214
215         return entry->rmid;
216 }
217
218 static void __put_rmid(u32 rmid)
219 {
220         struct cqm_rmid_entry *entry;
221
222         lockdep_assert_held(&cache_mutex);
223
224         WARN_ON(!__rmid_valid(rmid));
225         entry = __rmid_entry(rmid);
226
227         entry->queue_time = jiffies;
228         entry->state = RMID_YOUNG;
229
230         list_add_tail(&entry->list, &cqm_rmid_limbo_lru);
231 }
232
233 static void cqm_cleanup(void)
234 {
235         int i;
236
237         if (!cqm_rmid_ptrs)
238                 return;
239
240         for (i = 0; i < cqm_max_rmid; i++)
241                 kfree(cqm_rmid_ptrs[i]);
242
243         kfree(cqm_rmid_ptrs);
244         cqm_rmid_ptrs = NULL;
245         cqm_enabled = false;
246 }
247
248 static int intel_cqm_setup_rmid_cache(void)
249 {
250         struct cqm_rmid_entry *entry;
251         unsigned int nr_rmids;
252         int r = 0;
253
254         nr_rmids = cqm_max_rmid + 1;
255         cqm_rmid_ptrs = kzalloc(sizeof(struct cqm_rmid_entry *) *
256                                 nr_rmids, GFP_KERNEL);
257         if (!cqm_rmid_ptrs)
258                 return -ENOMEM;
259
260         for (; r <= cqm_max_rmid; r++) {
261                 struct cqm_rmid_entry *entry;
262
263                 entry = kmalloc(sizeof(*entry), GFP_KERNEL);
264                 if (!entry)
265                         goto fail;
266
267                 INIT_LIST_HEAD(&entry->list);
268                 entry->rmid = r;
269                 cqm_rmid_ptrs[r] = entry;
270
271                 list_add_tail(&entry->list, &cqm_rmid_free_lru);
272         }
273
274         /*
275          * RMID 0 is special and is always allocated. It's used for all
276          * tasks that are not monitored.
277          */
278         entry = __rmid_entry(0);
279         list_del(&entry->list);
280
281         mutex_lock(&cache_mutex);
282         intel_cqm_rotation_rmid = __get_rmid();
283         mutex_unlock(&cache_mutex);
284
285         return 0;
286
287 fail:
288         cqm_cleanup();
289         return -ENOMEM;
290 }
291
292 /*
293  * Determine if @a and @b measure the same set of tasks.
294  *
295  * If @a and @b measure the same set of tasks then we want to share a
296  * single RMID.
297  */
298 static bool __match_event(struct perf_event *a, struct perf_event *b)
299 {
300         /* Per-cpu and task events don't mix */
301         if ((a->attach_state & PERF_ATTACH_TASK) !=
302             (b->attach_state & PERF_ATTACH_TASK))
303                 return false;
304
305 #ifdef CONFIG_CGROUP_PERF
306         if (a->cgrp != b->cgrp)
307                 return false;
308 #endif
309
310         /* If not task event, we're machine wide */
311         if (!(b->attach_state & PERF_ATTACH_TASK))
312                 return true;
313
314         /*
315          * Events that target same task are placed into the same cache group.
316          * Mark it as a multi event group, so that we update ->count
317          * for every event rather than just the group leader later.
318          */
319         if (a->hw.target == b->hw.target) {
320                 b->hw.is_group_event = true;
321                 return true;
322         }
323
324         /*
325          * Are we an inherited event?
326          */
327         if (b->parent == a)
328                 return true;
329
330         return false;
331 }
332
333 #ifdef CONFIG_CGROUP_PERF
334 static inline struct perf_cgroup *event_to_cgroup(struct perf_event *event)
335 {
336         if (event->attach_state & PERF_ATTACH_TASK)
337                 return perf_cgroup_from_task(event->hw.target, event->ctx);
338
339         return event->cgrp;
340 }
341 #endif
342
343 /*
344  * Determine if @a's tasks intersect with @b's tasks
345  *
346  * There are combinations of events that we explicitly prohibit,
347  *
348  *                 PROHIBITS
349  *     system-wide    ->        cgroup and task
350  *     cgroup         ->        system-wide
351  *                    ->        task in cgroup
352  *     task           ->        system-wide
353  *                    ->        task in cgroup
354  *
355  * Call this function before allocating an RMID.
356  */
357 static bool __conflict_event(struct perf_event *a, struct perf_event *b)
358 {
359 #ifdef CONFIG_CGROUP_PERF
360         /*
361          * We can have any number of cgroups but only one system-wide
362          * event at a time.
363          */
364         if (a->cgrp && b->cgrp) {
365                 struct perf_cgroup *ac = a->cgrp;
366                 struct perf_cgroup *bc = b->cgrp;
367
368                 /*
369                  * This condition should have been caught in
370                  * __match_event() and we should be sharing an RMID.
371                  */
372                 WARN_ON_ONCE(ac == bc);
373
374                 if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
375                     cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
376                         return true;
377
378                 return false;
379         }
380
381         if (a->cgrp || b->cgrp) {
382                 struct perf_cgroup *ac, *bc;
383
384                 /*
385                  * cgroup and system-wide events are mutually exclusive
386                  */
387                 if ((a->cgrp && !(b->attach_state & PERF_ATTACH_TASK)) ||
388                     (b->cgrp && !(a->attach_state & PERF_ATTACH_TASK)))
389                         return true;
390
391                 /*
392                  * Ensure neither event is part of the other's cgroup
393                  */
394                 ac = event_to_cgroup(a);
395                 bc = event_to_cgroup(b);
396                 if (ac == bc)
397                         return true;
398
399                 /*
400                  * Must have cgroup and non-intersecting task events.
401                  */
402                 if (!ac || !bc)
403                         return false;
404
405                 /*
406                  * We have cgroup and task events, and the task belongs
407                  * to a cgroup. Check for for overlap.
408                  */
409                 if (cgroup_is_descendant(ac->css.cgroup, bc->css.cgroup) ||
410                     cgroup_is_descendant(bc->css.cgroup, ac->css.cgroup))
411                         return true;
412
413                 return false;
414         }
415 #endif
416         /*
417          * If one of them is not a task, same story as above with cgroups.
418          */
419         if (!(a->attach_state & PERF_ATTACH_TASK) ||
420             !(b->attach_state & PERF_ATTACH_TASK))
421                 return true;
422
423         /*
424          * Must be non-overlapping.
425          */
426         return false;
427 }
428
429 struct rmid_read {
430         u32 rmid;
431         atomic64_t value;
432 };
433
434 static void __intel_cqm_event_count(void *info);
435
436 /*
437  * Exchange the RMID of a group of events.
438  */
439 static u32 intel_cqm_xchg_rmid(struct perf_event *group, u32 rmid)
440 {
441         struct perf_event *event;
442         struct list_head *head = &group->hw.cqm_group_entry;
443         u32 old_rmid = group->hw.cqm_rmid;
444
445         lockdep_assert_held(&cache_mutex);
446
447         /*
448          * If our RMID is being deallocated, perform a read now.
449          */
450         if (__rmid_valid(old_rmid) && !__rmid_valid(rmid)) {
451                 struct rmid_read rr = {
452                         .value = ATOMIC64_INIT(0),
453                         .rmid = old_rmid,
454                 };
455
456                 on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count,
457                                  &rr, 1);
458                 local64_set(&group->count, atomic64_read(&rr.value));
459         }
460
461         raw_spin_lock_irq(&cache_lock);
462
463         group->hw.cqm_rmid = rmid;
464         list_for_each_entry(event, head, hw.cqm_group_entry)
465                 event->hw.cqm_rmid = rmid;
466
467         raw_spin_unlock_irq(&cache_lock);
468
469         return old_rmid;
470 }
471
472 /*
473  * If we fail to assign a new RMID for intel_cqm_rotation_rmid because
474  * cachelines are still tagged with RMIDs in limbo, we progressively
475  * increment the threshold until we find an RMID in limbo with <=
476  * __intel_cqm_threshold lines tagged. This is designed to mitigate the
477  * problem where cachelines tagged with an RMID are not steadily being
478  * evicted.
479  *
480  * On successful rotations we decrease the threshold back towards zero.
481  *
482  * __intel_cqm_max_threshold provides an upper bound on the threshold,
483  * and is measured in bytes because it's exposed to userland.
484  */
485 static unsigned int __intel_cqm_threshold;
486 static unsigned int __intel_cqm_max_threshold;
487
488 /*
489  * Test whether an RMID has a zero occupancy value on this cpu.
490  */
491 static void intel_cqm_stable(void *arg)
492 {
493         struct cqm_rmid_entry *entry;
494
495         list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
496                 if (entry->state != RMID_AVAILABLE)
497                         break;
498
499                 if (__rmid_read(entry->rmid) > __intel_cqm_threshold)
500                         entry->state = RMID_DIRTY;
501         }
502 }
503
504 /*
505  * If we have group events waiting for an RMID that don't conflict with
506  * events already running, assign @rmid.
507  */
508 static bool intel_cqm_sched_in_event(u32 rmid)
509 {
510         struct perf_event *leader, *event;
511
512         lockdep_assert_held(&cache_mutex);
513
514         leader = list_first_entry(&cache_groups, struct perf_event,
515                                   hw.cqm_groups_entry);
516         event = leader;
517
518         list_for_each_entry_continue(event, &cache_groups,
519                                      hw.cqm_groups_entry) {
520                 if (__rmid_valid(event->hw.cqm_rmid))
521                         continue;
522
523                 if (__conflict_event(event, leader))
524                         continue;
525
526                 intel_cqm_xchg_rmid(event, rmid);
527                 return true;
528         }
529
530         return false;
531 }
532
533 /*
534  * Initially use this constant for both the limbo queue time and the
535  * rotation timer interval, pmu::hrtimer_interval_ms.
536  *
537  * They don't need to be the same, but the two are related since if you
538  * rotate faster than you recycle RMIDs, you may run out of available
539  * RMIDs.
540  */
541 #define RMID_DEFAULT_QUEUE_TIME 250     /* ms */
542
543 static unsigned int __rmid_queue_time_ms = RMID_DEFAULT_QUEUE_TIME;
544
545 /*
546  * intel_cqm_rmid_stabilize - move RMIDs from limbo to free list
547  * @nr_available: number of freeable RMIDs on the limbo list
548  *
549  * Quiescent state; wait for all 'freed' RMIDs to become unused, i.e. no
550  * cachelines are tagged with those RMIDs. After this we can reuse them
551  * and know that the current set of active RMIDs is stable.
552  *
553  * Return %true or %false depending on whether stabilization needs to be
554  * reattempted.
555  *
556  * If we return %true then @nr_available is updated to indicate the
557  * number of RMIDs on the limbo list that have been queued for the
558  * minimum queue time (RMID_AVAILABLE), but whose data occupancy values
559  * are above __intel_cqm_threshold.
560  */
561 static bool intel_cqm_rmid_stabilize(unsigned int *available)
562 {
563         struct cqm_rmid_entry *entry, *tmp;
564
565         lockdep_assert_held(&cache_mutex);
566
567         *available = 0;
568         list_for_each_entry(entry, &cqm_rmid_limbo_lru, list) {
569                 unsigned long min_queue_time;
570                 unsigned long now = jiffies;
571
572                 /*
573                  * We hold RMIDs placed into limbo for a minimum queue
574                  * time. Before the minimum queue time has elapsed we do
575                  * not recycle RMIDs.
576                  *
577                  * The reasoning is that until a sufficient time has
578                  * passed since we stopped using an RMID, any RMID
579                  * placed onto the limbo list will likely still have
580                  * data tagged in the cache, which means we'll probably
581                  * fail to recycle it anyway.
582                  *
583                  * We can save ourselves an expensive IPI by skipping
584                  * any RMIDs that have not been queued for the minimum
585                  * time.
586                  */
587                 min_queue_time = entry->queue_time +
588                         msecs_to_jiffies(__rmid_queue_time_ms);
589
590                 if (time_after(min_queue_time, now))
591                         break;
592
593                 entry->state = RMID_AVAILABLE;
594                 (*available)++;
595         }
596
597         /*
598          * Fast return if none of the RMIDs on the limbo list have been
599          * sitting on the queue for the minimum queue time.
600          */
601         if (!*available)
602                 return false;
603
604         /*
605          * Test whether an RMID is free for each package.
606          */
607         on_each_cpu_mask(&cqm_cpumask, intel_cqm_stable, NULL, true);
608
609         list_for_each_entry_safe(entry, tmp, &cqm_rmid_limbo_lru, list) {
610                 /*
611                  * Exhausted all RMIDs that have waited min queue time.
612                  */
613                 if (entry->state == RMID_YOUNG)
614                         break;
615
616                 if (entry->state == RMID_DIRTY)
617                         continue;
618
619                 list_del(&entry->list); /* remove from limbo */
620
621                 /*
622                  * The rotation RMID gets priority if it's
623                  * currently invalid. In which case, skip adding
624                  * the RMID to the the free lru.
625                  */
626                 if (!__rmid_valid(intel_cqm_rotation_rmid)) {
627                         intel_cqm_rotation_rmid = entry->rmid;
628                         continue;
629                 }
630
631                 /*
632                  * If we have groups waiting for RMIDs, hand
633                  * them one now provided they don't conflict.
634                  */
635                 if (intel_cqm_sched_in_event(entry->rmid))
636                         continue;
637
638                 /*
639                  * Otherwise place it onto the free list.
640                  */
641                 list_add_tail(&entry->list, &cqm_rmid_free_lru);
642         }
643
644
645         return __rmid_valid(intel_cqm_rotation_rmid);
646 }
647
648 /*
649  * Pick a victim group and move it to the tail of the group list.
650  * @next: The first group without an RMID
651  */
652 static void __intel_cqm_pick_and_rotate(struct perf_event *next)
653 {
654         struct perf_event *rotor;
655         u32 rmid;
656
657         lockdep_assert_held(&cache_mutex);
658
659         rotor = list_first_entry(&cache_groups, struct perf_event,
660                                  hw.cqm_groups_entry);
661
662         /*
663          * The group at the front of the list should always have a valid
664          * RMID. If it doesn't then no groups have RMIDs assigned and we
665          * don't need to rotate the list.
666          */
667         if (next == rotor)
668                 return;
669
670         rmid = intel_cqm_xchg_rmid(rotor, INVALID_RMID);
671         __put_rmid(rmid);
672
673         list_rotate_left(&cache_groups);
674 }
675
676 /*
677  * Deallocate the RMIDs from any events that conflict with @event, and
678  * place them on the back of the group list.
679  */
680 static void intel_cqm_sched_out_conflicting_events(struct perf_event *event)
681 {
682         struct perf_event *group, *g;
683         u32 rmid;
684
685         lockdep_assert_held(&cache_mutex);
686
687         list_for_each_entry_safe(group, g, &cache_groups, hw.cqm_groups_entry) {
688                 if (group == event)
689                         continue;
690
691                 rmid = group->hw.cqm_rmid;
692
693                 /*
694                  * Skip events that don't have a valid RMID.
695                  */
696                 if (!__rmid_valid(rmid))
697                         continue;
698
699                 /*
700                  * No conflict? No problem! Leave the event alone.
701                  */
702                 if (!__conflict_event(group, event))
703                         continue;
704
705                 intel_cqm_xchg_rmid(group, INVALID_RMID);
706                 __put_rmid(rmid);
707         }
708 }
709
710 /*
711  * Attempt to rotate the groups and assign new RMIDs.
712  *
713  * We rotate for two reasons,
714  *   1. To handle the scheduling of conflicting events
715  *   2. To recycle RMIDs
716  *
717  * Rotating RMIDs is complicated because the hardware doesn't give us
718  * any clues.
719  *
720  * There's problems with the hardware interface; when you change the
721  * task:RMID map cachelines retain their 'old' tags, giving a skewed
722  * picture. In order to work around this, we must always keep one free
723  * RMID - intel_cqm_rotation_rmid.
724  *
725  * Rotation works by taking away an RMID from a group (the old RMID),
726  * and assigning the free RMID to another group (the new RMID). We must
727  * then wait for the old RMID to not be used (no cachelines tagged).
728  * This ensure that all cachelines are tagged with 'active' RMIDs. At
729  * this point we can start reading values for the new RMID and treat the
730  * old RMID as the free RMID for the next rotation.
731  *
732  * Return %true or %false depending on whether we did any rotating.
733  */
734 static bool __intel_cqm_rmid_rotate(void)
735 {
736         struct perf_event *group, *start = NULL;
737         unsigned int threshold_limit;
738         unsigned int nr_needed = 0;
739         unsigned int nr_available;
740         bool rotated = false;
741
742         mutex_lock(&cache_mutex);
743
744 again:
745         /*
746          * Fast path through this function if there are no groups and no
747          * RMIDs that need cleaning.
748          */
749         if (list_empty(&cache_groups) && list_empty(&cqm_rmid_limbo_lru))
750                 goto out;
751
752         list_for_each_entry(group, &cache_groups, hw.cqm_groups_entry) {
753                 if (!__rmid_valid(group->hw.cqm_rmid)) {
754                         if (!start)
755                                 start = group;
756                         nr_needed++;
757                 }
758         }
759
760         /*
761          * We have some event groups, but they all have RMIDs assigned
762          * and no RMIDs need cleaning.
763          */
764         if (!nr_needed && list_empty(&cqm_rmid_limbo_lru))
765                 goto out;
766
767         if (!nr_needed)
768                 goto stabilize;
769
770         /*
771          * We have more event groups without RMIDs than available RMIDs,
772          * or we have event groups that conflict with the ones currently
773          * scheduled.
774          *
775          * We force deallocate the rmid of the group at the head of
776          * cache_groups. The first event group without an RMID then gets
777          * assigned intel_cqm_rotation_rmid. This ensures we always make
778          * forward progress.
779          *
780          * Rotate the cache_groups list so the previous head is now the
781          * tail.
782          */
783         __intel_cqm_pick_and_rotate(start);
784
785         /*
786          * If the rotation is going to succeed, reduce the threshold so
787          * that we don't needlessly reuse dirty RMIDs.
788          */
789         if (__rmid_valid(intel_cqm_rotation_rmid)) {
790                 intel_cqm_xchg_rmid(start, intel_cqm_rotation_rmid);
791                 intel_cqm_rotation_rmid = __get_rmid();
792
793                 intel_cqm_sched_out_conflicting_events(start);
794
795                 if (__intel_cqm_threshold)
796                         __intel_cqm_threshold--;
797         }
798
799         rotated = true;
800
801 stabilize:
802         /*
803          * We now need to stablize the RMID we freed above (if any) to
804          * ensure that the next time we rotate we have an RMID with zero
805          * occupancy value.
806          *
807          * Alternatively, if we didn't need to perform any rotation,
808          * we'll have a bunch of RMIDs in limbo that need stabilizing.
809          */
810         threshold_limit = __intel_cqm_max_threshold / cqm_l3_scale;
811
812         while (intel_cqm_rmid_stabilize(&nr_available) &&
813                __intel_cqm_threshold < threshold_limit) {
814                 unsigned int steal_limit;
815
816                 /*
817                  * Don't spin if nobody is actively waiting for an RMID,
818                  * the rotation worker will be kicked as soon as an
819                  * event needs an RMID anyway.
820                  */
821                 if (!nr_needed)
822                         break;
823
824                 /* Allow max 25% of RMIDs to be in limbo. */
825                 steal_limit = (cqm_max_rmid + 1) / 4;
826
827                 /*
828                  * We failed to stabilize any RMIDs so our rotation
829                  * logic is now stuck. In order to make forward progress
830                  * we have a few options:
831                  *
832                  *   1. rotate ("steal") another RMID
833                  *   2. increase the threshold
834                  *   3. do nothing
835                  *
836                  * We do both of 1. and 2. until we hit the steal limit.
837                  *
838                  * The steal limit prevents all RMIDs ending up on the
839                  * limbo list. This can happen if every RMID has a
840                  * non-zero occupancy above threshold_limit, and the
841                  * occupancy values aren't dropping fast enough.
842                  *
843                  * Note that there is prioritisation at work here - we'd
844                  * rather increase the number of RMIDs on the limbo list
845                  * than increase the threshold, because increasing the
846                  * threshold skews the event data (because we reuse
847                  * dirty RMIDs) - threshold bumps are a last resort.
848                  */
849                 if (nr_available < steal_limit)
850                         goto again;
851
852                 __intel_cqm_threshold++;
853         }
854
855 out:
856         mutex_unlock(&cache_mutex);
857         return rotated;
858 }
859
860 static void intel_cqm_rmid_rotate(struct work_struct *work);
861
862 static DECLARE_DELAYED_WORK(intel_cqm_rmid_work, intel_cqm_rmid_rotate);
863
864 static struct pmu intel_cqm_pmu;
865
866 static void intel_cqm_rmid_rotate(struct work_struct *work)
867 {
868         unsigned long delay;
869
870         __intel_cqm_rmid_rotate();
871
872         delay = msecs_to_jiffies(intel_cqm_pmu.hrtimer_interval_ms);
873         schedule_delayed_work(&intel_cqm_rmid_work, delay);
874 }
875
876 /*
877  * Find a group and setup RMID.
878  *
879  * If we're part of a group, we use the group's RMID.
880  */
881 static void intel_cqm_setup_event(struct perf_event *event,
882                                   struct perf_event **group)
883 {
884         struct perf_event *iter;
885         bool conflict = false;
886         u32 rmid;
887
888         event->hw.is_group_event = false;
889         list_for_each_entry(iter, &cache_groups, hw.cqm_groups_entry) {
890                 rmid = iter->hw.cqm_rmid;
891
892                 if (__match_event(iter, event)) {
893                         /* All tasks in a group share an RMID */
894                         event->hw.cqm_rmid = rmid;
895                         *group = iter;
896                         return;
897                 }
898
899                 /*
900                  * We only care about conflicts for events that are
901                  * actually scheduled in (and hence have a valid RMID).
902                  */
903                 if (__conflict_event(iter, event) && __rmid_valid(rmid))
904                         conflict = true;
905         }
906
907         if (conflict)
908                 rmid = INVALID_RMID;
909         else
910                 rmid = __get_rmid();
911
912         event->hw.cqm_rmid = rmid;
913 }
914
915 static void intel_cqm_event_read(struct perf_event *event)
916 {
917         unsigned long flags;
918         u32 rmid;
919         u64 val;
920
921         /*
922          * Task events are handled by intel_cqm_event_count().
923          */
924         if (event->cpu == -1)
925                 return;
926
927         raw_spin_lock_irqsave(&cache_lock, flags);
928         rmid = event->hw.cqm_rmid;
929
930         if (!__rmid_valid(rmid))
931                 goto out;
932
933         val = __rmid_read(rmid);
934
935         /*
936          * Ignore this reading on error states and do not update the value.
937          */
938         if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
939                 goto out;
940
941         local64_set(&event->count, val);
942 out:
943         raw_spin_unlock_irqrestore(&cache_lock, flags);
944 }
945
946 static void __intel_cqm_event_count(void *info)
947 {
948         struct rmid_read *rr = info;
949         u64 val;
950
951         val = __rmid_read(rr->rmid);
952
953         if (val & (RMID_VAL_ERROR | RMID_VAL_UNAVAIL))
954                 return;
955
956         atomic64_add(val, &rr->value);
957 }
958
959 static inline bool cqm_group_leader(struct perf_event *event)
960 {
961         return !list_empty(&event->hw.cqm_groups_entry);
962 }
963
964 static u64 intel_cqm_event_count(struct perf_event *event)
965 {
966         unsigned long flags;
967         struct rmid_read rr = {
968                 .value = ATOMIC64_INIT(0),
969         };
970
971         /*
972          * We only need to worry about task events. System-wide events
973          * are handled like usual, i.e. entirely with
974          * intel_cqm_event_read().
975          */
976         if (event->cpu != -1)
977                 return __perf_event_count(event);
978
979         /*
980          * Only the group leader gets to report values except in case of
981          * multiple events in the same group, we still need to read the
982          * other events.This stops us
983          * reporting duplicate values to userspace, and gives us a clear
984          * rule for which task gets to report the values.
985          *
986          * Note that it is impossible to attribute these values to
987          * specific packages - we forfeit that ability when we create
988          * task events.
989          */
990         if (!cqm_group_leader(event) && !event->hw.is_group_event)
991                 return 0;
992
993         /*
994          * Getting up-to-date values requires an SMP IPI which is not
995          * possible if we're being called in interrupt context. Return
996          * the cached values instead.
997          */
998         if (unlikely(in_interrupt()))
999                 goto out;
1000
1001         /*
1002          * Notice that we don't perform the reading of an RMID
1003          * atomically, because we can't hold a spin lock across the
1004          * IPIs.
1005          *
1006          * Speculatively perform the read, since @event might be
1007          * assigned a different (possibly invalid) RMID while we're
1008          * busying performing the IPI calls. It's therefore necessary to
1009          * check @event's RMID afterwards, and if it has changed,
1010          * discard the result of the read.
1011          */
1012         rr.rmid = ACCESS_ONCE(event->hw.cqm_rmid);
1013
1014         if (!__rmid_valid(rr.rmid))
1015                 goto out;
1016
1017         on_each_cpu_mask(&cqm_cpumask, __intel_cqm_event_count, &rr, 1);
1018
1019         raw_spin_lock_irqsave(&cache_lock, flags);
1020         if (event->hw.cqm_rmid == rr.rmid)
1021                 local64_set(&event->count, atomic64_read(&rr.value));
1022         raw_spin_unlock_irqrestore(&cache_lock, flags);
1023 out:
1024         return __perf_event_count(event);
1025 }
1026
1027 static void intel_cqm_event_start(struct perf_event *event, int mode)
1028 {
1029         struct intel_pqr_state *state = this_cpu_ptr(&pqr_state);
1030         u32 rmid = event->hw.cqm_rmid;
1031
1032         if (!(event->hw.cqm_state & PERF_HES_STOPPED))
1033                 return;
1034
1035         event->hw.cqm_state &= ~PERF_HES_STOPPED;
1036
1037         if (state->rmid_usecnt++) {
1038                 if (!WARN_ON_ONCE(state->rmid != rmid))
1039                         return;
1040         } else {
1041                 WARN_ON_ONCE(state->rmid);
1042         }
1043
1044         state->rmid = rmid;
1045         wrmsr(MSR_IA32_PQR_ASSOC, rmid, state->closid);
1046 }
1047
1048 static void intel_cqm_event_stop(struct perf_event *event, int mode)
1049 {
1050         struct intel_pqr_state *state = this_cpu_ptr(&pqr_state);
1051
1052         if (event->hw.cqm_state & PERF_HES_STOPPED)
1053                 return;
1054
1055         event->hw.cqm_state |= PERF_HES_STOPPED;
1056
1057         intel_cqm_event_read(event);
1058
1059         if (!--state->rmid_usecnt) {
1060                 state->rmid = 0;
1061                 wrmsr(MSR_IA32_PQR_ASSOC, 0, state->closid);
1062         } else {
1063                 WARN_ON_ONCE(!state->rmid);
1064         }
1065 }
1066
1067 static int intel_cqm_event_add(struct perf_event *event, int mode)
1068 {
1069         unsigned long flags;
1070         u32 rmid;
1071
1072         raw_spin_lock_irqsave(&cache_lock, flags);
1073
1074         event->hw.cqm_state = PERF_HES_STOPPED;
1075         rmid = event->hw.cqm_rmid;
1076
1077         if (__rmid_valid(rmid) && (mode & PERF_EF_START))
1078                 intel_cqm_event_start(event, mode);
1079
1080         raw_spin_unlock_irqrestore(&cache_lock, flags);
1081
1082         return 0;
1083 }
1084
1085 static void intel_cqm_event_destroy(struct perf_event *event)
1086 {
1087         struct perf_event *group_other = NULL;
1088
1089         mutex_lock(&cache_mutex);
1090
1091         /*
1092          * If there's another event in this group...
1093          */
1094         if (!list_empty(&event->hw.cqm_group_entry)) {
1095                 group_other = list_first_entry(&event->hw.cqm_group_entry,
1096                                                struct perf_event,
1097                                                hw.cqm_group_entry);
1098                 list_del(&event->hw.cqm_group_entry);
1099         }
1100
1101         /*
1102          * And we're the group leader..
1103          */
1104         if (cqm_group_leader(event)) {
1105                 /*
1106                  * If there was a group_other, make that leader, otherwise
1107                  * destroy the group and return the RMID.
1108                  */
1109                 if (group_other) {
1110                         list_replace(&event->hw.cqm_groups_entry,
1111                                      &group_other->hw.cqm_groups_entry);
1112                 } else {
1113                         u32 rmid = event->hw.cqm_rmid;
1114
1115                         if (__rmid_valid(rmid))
1116                                 __put_rmid(rmid);
1117                         list_del(&event->hw.cqm_groups_entry);
1118                 }
1119         }
1120
1121         mutex_unlock(&cache_mutex);
1122 }
1123
1124 static int intel_cqm_event_init(struct perf_event *event)
1125 {
1126         struct perf_event *group = NULL;
1127         bool rotate = false;
1128
1129         if (event->attr.type != intel_cqm_pmu.type)
1130                 return -ENOENT;
1131
1132         if (event->attr.config & ~QOS_EVENT_MASK)
1133                 return -EINVAL;
1134
1135         /* unsupported modes and filters */
1136         if (event->attr.exclude_user   ||
1137             event->attr.exclude_kernel ||
1138             event->attr.exclude_hv     ||
1139             event->attr.exclude_idle   ||
1140             event->attr.exclude_host   ||
1141             event->attr.exclude_guest  ||
1142             event->attr.sample_period) /* no sampling */
1143                 return -EINVAL;
1144
1145         INIT_LIST_HEAD(&event->hw.cqm_group_entry);
1146         INIT_LIST_HEAD(&event->hw.cqm_groups_entry);
1147
1148         event->destroy = intel_cqm_event_destroy;
1149
1150         mutex_lock(&cache_mutex);
1151
1152         /* Will also set rmid */
1153         intel_cqm_setup_event(event, &group);
1154
1155         if (group) {
1156                 list_add_tail(&event->hw.cqm_group_entry,
1157                               &group->hw.cqm_group_entry);
1158         } else {
1159                 list_add_tail(&event->hw.cqm_groups_entry,
1160                               &cache_groups);
1161
1162                 /*
1163                  * All RMIDs are either in use or have recently been
1164                  * used. Kick the rotation worker to clean/free some.
1165                  *
1166                  * We only do this for the group leader, rather than for
1167                  * every event in a group to save on needless work.
1168                  */
1169                 if (!__rmid_valid(event->hw.cqm_rmid))
1170                         rotate = true;
1171         }
1172
1173         mutex_unlock(&cache_mutex);
1174
1175         if (rotate)
1176                 schedule_delayed_work(&intel_cqm_rmid_work, 0);
1177
1178         return 0;
1179 }
1180
1181 EVENT_ATTR_STR(llc_occupancy, intel_cqm_llc, "event=0x01");
1182 EVENT_ATTR_STR(llc_occupancy.per-pkg, intel_cqm_llc_pkg, "1");
1183 EVENT_ATTR_STR(llc_occupancy.unit, intel_cqm_llc_unit, "Bytes");
1184 EVENT_ATTR_STR(llc_occupancy.scale, intel_cqm_llc_scale, NULL);
1185 EVENT_ATTR_STR(llc_occupancy.snapshot, intel_cqm_llc_snapshot, "1");
1186
1187 EVENT_ATTR_STR(total_bytes, intel_cqm_total_bytes, "event=0x02");
1188 EVENT_ATTR_STR(total_bytes.per-pkg, intel_cqm_total_bytes_pkg, "1");
1189 EVENT_ATTR_STR(total_bytes.unit, intel_cqm_total_bytes_unit, "MB");
1190 EVENT_ATTR_STR(total_bytes.scale, intel_cqm_total_bytes_scale, "1e-6");
1191
1192 EVENT_ATTR_STR(local_bytes, intel_cqm_local_bytes, "event=0x03");
1193 EVENT_ATTR_STR(local_bytes.per-pkg, intel_cqm_local_bytes_pkg, "1");
1194 EVENT_ATTR_STR(local_bytes.unit, intel_cqm_local_bytes_unit, "MB");
1195 EVENT_ATTR_STR(local_bytes.scale, intel_cqm_local_bytes_scale, "1e-6");
1196
1197 static struct attribute *intel_cqm_events_attr[] = {
1198         EVENT_PTR(intel_cqm_llc),
1199         EVENT_PTR(intel_cqm_llc_pkg),
1200         EVENT_PTR(intel_cqm_llc_unit),
1201         EVENT_PTR(intel_cqm_llc_scale),
1202         EVENT_PTR(intel_cqm_llc_snapshot),
1203         NULL,
1204 };
1205
1206 static struct attribute *intel_mbm_events_attr[] = {
1207         EVENT_PTR(intel_cqm_total_bytes),
1208         EVENT_PTR(intel_cqm_local_bytes),
1209         EVENT_PTR(intel_cqm_total_bytes_pkg),
1210         EVENT_PTR(intel_cqm_local_bytes_pkg),
1211         EVENT_PTR(intel_cqm_total_bytes_unit),
1212         EVENT_PTR(intel_cqm_local_bytes_unit),
1213         EVENT_PTR(intel_cqm_total_bytes_scale),
1214         EVENT_PTR(intel_cqm_local_bytes_scale),
1215         NULL,
1216 };
1217
1218 static struct attribute *intel_cmt_mbm_events_attr[] = {
1219         EVENT_PTR(intel_cqm_llc),
1220         EVENT_PTR(intel_cqm_total_bytes),
1221         EVENT_PTR(intel_cqm_local_bytes),
1222         EVENT_PTR(intel_cqm_llc_pkg),
1223         EVENT_PTR(intel_cqm_total_bytes_pkg),
1224         EVENT_PTR(intel_cqm_local_bytes_pkg),
1225         EVENT_PTR(intel_cqm_llc_unit),
1226         EVENT_PTR(intel_cqm_total_bytes_unit),
1227         EVENT_PTR(intel_cqm_local_bytes_unit),
1228         EVENT_PTR(intel_cqm_llc_scale),
1229         EVENT_PTR(intel_cqm_total_bytes_scale),
1230         EVENT_PTR(intel_cqm_local_bytes_scale),
1231         EVENT_PTR(intel_cqm_llc_snapshot),
1232         NULL,
1233 };
1234
1235 static struct attribute_group intel_cqm_events_group = {
1236         .name = "events",
1237         .attrs = NULL,
1238 };
1239
1240 PMU_FORMAT_ATTR(event, "config:0-7");
1241 static struct attribute *intel_cqm_formats_attr[] = {
1242         &format_attr_event.attr,
1243         NULL,
1244 };
1245
1246 static struct attribute_group intel_cqm_format_group = {
1247         .name = "format",
1248         .attrs = intel_cqm_formats_attr,
1249 };
1250
1251 static ssize_t
1252 max_recycle_threshold_show(struct device *dev, struct device_attribute *attr,
1253                            char *page)
1254 {
1255         ssize_t rv;
1256
1257         mutex_lock(&cache_mutex);
1258         rv = snprintf(page, PAGE_SIZE-1, "%u\n", __intel_cqm_max_threshold);
1259         mutex_unlock(&cache_mutex);
1260
1261         return rv;
1262 }
1263
1264 static ssize_t
1265 max_recycle_threshold_store(struct device *dev,
1266                             struct device_attribute *attr,
1267                             const char *buf, size_t count)
1268 {
1269         unsigned int bytes, cachelines;
1270         int ret;
1271
1272         ret = kstrtouint(buf, 0, &bytes);
1273         if (ret)
1274                 return ret;
1275
1276         mutex_lock(&cache_mutex);
1277
1278         __intel_cqm_max_threshold = bytes;
1279         cachelines = bytes / cqm_l3_scale;
1280
1281         /*
1282          * The new maximum takes effect immediately.
1283          */
1284         if (__intel_cqm_threshold > cachelines)
1285                 __intel_cqm_threshold = cachelines;
1286
1287         mutex_unlock(&cache_mutex);
1288
1289         return count;
1290 }
1291
1292 static DEVICE_ATTR_RW(max_recycle_threshold);
1293
1294 static struct attribute *intel_cqm_attrs[] = {
1295         &dev_attr_max_recycle_threshold.attr,
1296         NULL,
1297 };
1298
1299 static const struct attribute_group intel_cqm_group = {
1300         .attrs = intel_cqm_attrs,
1301 };
1302
1303 static const struct attribute_group *intel_cqm_attr_groups[] = {
1304         &intel_cqm_events_group,
1305         &intel_cqm_format_group,
1306         &intel_cqm_group,
1307         NULL,
1308 };
1309
1310 static struct pmu intel_cqm_pmu = {
1311         .hrtimer_interval_ms = RMID_DEFAULT_QUEUE_TIME,
1312         .attr_groups         = intel_cqm_attr_groups,
1313         .task_ctx_nr         = perf_sw_context,
1314         .event_init          = intel_cqm_event_init,
1315         .add                 = intel_cqm_event_add,
1316         .del                 = intel_cqm_event_stop,
1317         .start               = intel_cqm_event_start,
1318         .stop                = intel_cqm_event_stop,
1319         .read                = intel_cqm_event_read,
1320         .count               = intel_cqm_event_count,
1321 };
1322
1323 static inline void cqm_pick_event_reader(int cpu)
1324 {
1325         int reader;
1326
1327         /* First online cpu in package becomes the reader */
1328         reader = cpumask_any_and(&cqm_cpumask, topology_core_cpumask(cpu));
1329         if (reader >= nr_cpu_ids)
1330                 cpumask_set_cpu(cpu, &cqm_cpumask);
1331 }
1332
1333 static void intel_cqm_cpu_starting(unsigned int cpu)
1334 {
1335         struct intel_pqr_state *state = &per_cpu(pqr_state, cpu);
1336         struct cpuinfo_x86 *c = &cpu_data(cpu);
1337
1338         state->rmid = 0;
1339         state->closid = 0;
1340         state->rmid_usecnt = 0;
1341
1342         WARN_ON(c->x86_cache_max_rmid != cqm_max_rmid);
1343         WARN_ON(c->x86_cache_occ_scale != cqm_l3_scale);
1344 }
1345
1346 static void intel_cqm_cpu_exit(unsigned int cpu)
1347 {
1348         int target;
1349
1350         /* Is @cpu the current cqm reader for this package ? */
1351         if (!cpumask_test_and_clear_cpu(cpu, &cqm_cpumask))
1352                 return;
1353
1354         /* Find another online reader in this package */
1355         target = cpumask_any_but(topology_core_cpumask(cpu), cpu);
1356
1357         if (target < nr_cpu_ids)
1358                 cpumask_set_cpu(target, &cqm_cpumask);
1359 }
1360
1361 static int intel_cqm_cpu_notifier(struct notifier_block *nb,
1362                                   unsigned long action, void *hcpu)
1363 {
1364         unsigned int cpu  = (unsigned long)hcpu;
1365
1366         switch (action & ~CPU_TASKS_FROZEN) {
1367         case CPU_DOWN_PREPARE:
1368                 intel_cqm_cpu_exit(cpu);
1369                 break;
1370         case CPU_STARTING:
1371                 intel_cqm_cpu_starting(cpu);
1372                 cqm_pick_event_reader(cpu);
1373                 break;
1374         }
1375
1376         return NOTIFY_OK;
1377 }
1378
1379 static const struct x86_cpu_id intel_cqm_match[] = {
1380         { .vendor = X86_VENDOR_INTEL, .feature = X86_FEATURE_CQM_OCCUP_LLC },
1381         {}
1382 };
1383
1384 static void mbm_cleanup(void)
1385 {
1386         if (!mbm_enabled)
1387                 return;
1388
1389         kfree(mbm_local);
1390         kfree(mbm_total);
1391         mbm_enabled = false;
1392 }
1393
1394 static const struct x86_cpu_id intel_mbm_local_match[] = {
1395         { .vendor = X86_VENDOR_INTEL, .feature = X86_FEATURE_CQM_MBM_LOCAL },
1396         {}
1397 };
1398
1399 static const struct x86_cpu_id intel_mbm_total_match[] = {
1400         { .vendor = X86_VENDOR_INTEL, .feature = X86_FEATURE_CQM_MBM_TOTAL },
1401         {}
1402 };
1403
1404 static int intel_mbm_init(void)
1405 {
1406         int array_size, maxid = cqm_max_rmid + 1;
1407
1408         array_size = sizeof(struct sample) * maxid * topology_max_packages();
1409         mbm_local = kmalloc(array_size, GFP_KERNEL);
1410         if (!mbm_local)
1411                 return -ENOMEM;
1412
1413         mbm_total = kmalloc(array_size, GFP_KERNEL);
1414         if (!mbm_total) {
1415                 mbm_cleanup();
1416                 return -ENOMEM;
1417         }
1418
1419         return 0;
1420 }
1421
1422 static int __init intel_cqm_init(void)
1423 {
1424         char *str = NULL, scale[20];
1425         int i, cpu, ret;
1426
1427         if (x86_match_cpu(intel_cqm_match))
1428                 cqm_enabled = true;
1429
1430         if (x86_match_cpu(intel_mbm_local_match) &&
1431              x86_match_cpu(intel_mbm_total_match))
1432                 mbm_enabled = true;
1433
1434         if (!cqm_enabled && !mbm_enabled)
1435                 return -ENODEV;
1436
1437         cqm_l3_scale = boot_cpu_data.x86_cache_occ_scale;
1438
1439         /*
1440          * It's possible that not all resources support the same number
1441          * of RMIDs. Instead of making scheduling much more complicated
1442          * (where we have to match a task's RMID to a cpu that supports
1443          * that many RMIDs) just find the minimum RMIDs supported across
1444          * all cpus.
1445          *
1446          * Also, check that the scales match on all cpus.
1447          */
1448         cpu_notifier_register_begin();
1449
1450         for_each_online_cpu(cpu) {
1451                 struct cpuinfo_x86 *c = &cpu_data(cpu);
1452
1453                 if (c->x86_cache_max_rmid < cqm_max_rmid)
1454                         cqm_max_rmid = c->x86_cache_max_rmid;
1455
1456                 if (c->x86_cache_occ_scale != cqm_l3_scale) {
1457                         pr_err("Multiple LLC scale values, disabling\n");
1458                         ret = -EINVAL;
1459                         goto out;
1460                 }
1461         }
1462
1463         /*
1464          * A reasonable upper limit on the max threshold is the number
1465          * of lines tagged per RMID if all RMIDs have the same number of
1466          * lines tagged in the LLC.
1467          *
1468          * For a 35MB LLC and 56 RMIDs, this is ~1.8% of the LLC.
1469          */
1470         __intel_cqm_max_threshold =
1471                 boot_cpu_data.x86_cache_size * 1024 / (cqm_max_rmid + 1);
1472
1473         snprintf(scale, sizeof(scale), "%u", cqm_l3_scale);
1474         str = kstrdup(scale, GFP_KERNEL);
1475         if (!str) {
1476                 ret = -ENOMEM;
1477                 goto out;
1478         }
1479
1480         event_attr_intel_cqm_llc_scale.event_str = str;
1481
1482         ret = intel_cqm_setup_rmid_cache();
1483         if (ret)
1484                 goto out;
1485
1486         for_each_online_cpu(i) {
1487                 intel_cqm_cpu_starting(i);
1488                 cqm_pick_event_reader(i);
1489         }
1490
1491         if (mbm_enabled)
1492                 ret = intel_mbm_init();
1493         if (ret && !cqm_enabled)
1494                 goto out;
1495
1496         if (cqm_enabled && mbm_enabled)
1497                 intel_cqm_events_group.attrs = intel_cmt_mbm_events_attr;
1498         else if (!cqm_enabled && mbm_enabled)
1499                 intel_cqm_events_group.attrs = intel_mbm_events_attr;
1500         else if (cqm_enabled && !mbm_enabled)
1501                 intel_cqm_events_group.attrs = intel_cqm_events_attr;
1502
1503         ret = perf_pmu_register(&intel_cqm_pmu, "intel_cqm", -1);
1504         if (ret) {
1505                 pr_err("Intel CQM perf registration failed: %d\n", ret);
1506                 goto out;
1507         }
1508
1509         if (cqm_enabled)
1510                 pr_info("Intel CQM monitoring enabled\n");
1511         if (mbm_enabled)
1512                 pr_info("Intel MBM enabled\n");
1513
1514         /*
1515          * Register the hot cpu notifier once we are sure cqm
1516          * is enabled to avoid notifier leak.
1517          */
1518         __perf_cpu_notifier(intel_cqm_cpu_notifier);
1519 out:
1520         cpu_notifier_register_done();
1521         if (ret) {
1522                 kfree(str);
1523                 cqm_cleanup();
1524                 mbm_cleanup();
1525         }
1526
1527         return ret;
1528 }
1529 device_initcall(intel_cqm_init);