Mention branches and keyring.
[releases.git] / x86 / events / amd / ibs.c
1 /*
2  * Performance events - AMD IBS
3  *
4  *  Copyright (C) 2011 Advanced Micro Devices, Inc., Robert Richter
5  *
6  *  For licencing details see kernel-base/COPYING
7  */
8
9 #include <linux/perf_event.h>
10 #include <linux/init.h>
11 #include <linux/export.h>
12 #include <linux/pci.h>
13 #include <linux/ptrace.h>
14 #include <linux/syscore_ops.h>
15 #include <linux/sched/clock.h>
16
17 #include <asm/apic.h>
18
19 #include "../perf_event.h"
20
21 static u32 ibs_caps;
22
23 #if defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_AMD)
24
25 #include <linux/kprobes.h>
26 #include <linux/hardirq.h>
27
28 #include <asm/nmi.h>
29 #include <asm/amd-ibs.h>
30
31 #define IBS_FETCH_CONFIG_MASK   (IBS_FETCH_RAND_EN | IBS_FETCH_MAX_CNT)
32 #define IBS_OP_CONFIG_MASK      IBS_OP_MAX_CNT
33
34
35 /*
36  * IBS states:
37  *
38  * ENABLED; tracks the pmu::add(), pmu::del() state, when set the counter is taken
39  * and any further add()s must fail.
40  *
41  * STARTED/STOPPING/STOPPED; deal with pmu::start(), pmu::stop() state but are
42  * complicated by the fact that the IBS hardware can send late NMIs (ie. after
43  * we've cleared the EN bit).
44  *
45  * In order to consume these late NMIs we have the STOPPED state, any NMI that
46  * happens after we've cleared the EN state will clear this bit and report the
47  * NMI handled (this is fundamentally racy in the face or multiple NMI sources,
48  * someone else can consume our BIT and our NMI will go unhandled).
49  *
50  * And since we cannot set/clear this separate bit together with the EN bit,
51  * there are races; if we cleared STARTED early, an NMI could land in
52  * between clearing STARTED and clearing the EN bit (in fact multiple NMIs
53  * could happen if the period is small enough), and consume our STOPPED bit
54  * and trigger streams of unhandled NMIs.
55  *
56  * If, however, we clear STARTED late, an NMI can hit between clearing the
57  * EN bit and clearing STARTED, still see STARTED set and process the event.
58  * If this event will have the VALID bit clear, we bail properly, but this
59  * is not a given. With VALID set we can end up calling pmu::stop() again
60  * (the throttle logic) and trigger the WARNs in there.
61  *
62  * So what we do is set STOPPING before clearing EN to avoid the pmu::stop()
63  * nesting, and clear STARTED late, so that we have a well defined state over
64  * the clearing of the EN bit.
65  *
66  * XXX: we could probably be using !atomic bitops for all this.
67  */
68
69 enum ibs_states {
70         IBS_ENABLED     = 0,
71         IBS_STARTED     = 1,
72         IBS_STOPPING    = 2,
73         IBS_STOPPED     = 3,
74
75         IBS_MAX_STATES,
76 };
77
78 struct cpu_perf_ibs {
79         struct perf_event       *event;
80         unsigned long           state[BITS_TO_LONGS(IBS_MAX_STATES)];
81 };
82
83 struct perf_ibs {
84         struct pmu                      pmu;
85         unsigned int                    msr;
86         u64                             config_mask;
87         u64                             cnt_mask;
88         u64                             enable_mask;
89         u64                             valid_mask;
90         u64                             max_period;
91         unsigned long                   offset_mask[1];
92         int                             offset_max;
93         unsigned int                    fetch_count_reset_broken : 1;
94         unsigned int                    fetch_ignore_if_zero_rip : 1;
95         struct cpu_perf_ibs __percpu    *pcpu;
96
97         u64                             (*get_count)(u64 config);
98 };
99
100 static int
101 perf_event_set_period(struct hw_perf_event *hwc, u64 min, u64 max, u64 *hw_period)
102 {
103         s64 left = local64_read(&hwc->period_left);
104         s64 period = hwc->sample_period;
105         int overflow = 0;
106
107         /*
108          * If we are way outside a reasonable range then just skip forward:
109          */
110         if (unlikely(left <= -period)) {
111                 left = period;
112                 local64_set(&hwc->period_left, left);
113                 hwc->last_period = period;
114                 overflow = 1;
115         }
116
117         if (unlikely(left < (s64)min)) {
118                 left += period;
119                 local64_set(&hwc->period_left, left);
120                 hwc->last_period = period;
121                 overflow = 1;
122         }
123
124         /*
125          * If the hw period that triggers the sw overflow is too short
126          * we might hit the irq handler. This biases the results.
127          * Thus we shorten the next-to-last period and set the last
128          * period to the max period.
129          */
130         if (left > max) {
131                 left -= max;
132                 if (left > max)
133                         left = max;
134                 else if (left < min)
135                         left = min;
136         }
137
138         *hw_period = (u64)left;
139
140         return overflow;
141 }
142
143 static  int
144 perf_event_try_update(struct perf_event *event, u64 new_raw_count, int width)
145 {
146         struct hw_perf_event *hwc = &event->hw;
147         int shift = 64 - width;
148         u64 prev_raw_count;
149         u64 delta;
150
151         /*
152          * Careful: an NMI might modify the previous event value.
153          *
154          * Our tactic to handle this is to first atomically read and
155          * exchange a new raw count - then add that new-prev delta
156          * count to the generic event atomically:
157          */
158         prev_raw_count = local64_read(&hwc->prev_count);
159         if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
160                                         new_raw_count) != prev_raw_count)
161                 return 0;
162
163         /*
164          * Now we have the new raw value and have updated the prev
165          * timestamp already. We can now calculate the elapsed delta
166          * (event-)time and add that to the generic event.
167          *
168          * Careful, not all hw sign-extends above the physical width
169          * of the count.
170          */
171         delta = (new_raw_count << shift) - (prev_raw_count << shift);
172         delta >>= shift;
173
174         local64_add(delta, &event->count);
175         local64_sub(delta, &hwc->period_left);
176
177         return 1;
178 }
179
180 static struct perf_ibs perf_ibs_fetch;
181 static struct perf_ibs perf_ibs_op;
182
183 static struct perf_ibs *get_ibs_pmu(int type)
184 {
185         if (perf_ibs_fetch.pmu.type == type)
186                 return &perf_ibs_fetch;
187         if (perf_ibs_op.pmu.type == type)
188                 return &perf_ibs_op;
189         return NULL;
190 }
191
192 /*
193  * core pmu config -> IBS config
194  *
195  *  perf record -a -e cpu-cycles:p ...    # use ibs op counting cycle count
196  *  perf record -a -e r076:p ...          # same as -e cpu-cycles:p
197  *  perf record -a -e r0C1:p ...          # use ibs op counting micro-ops
198  *
199  * IbsOpCntCtl (bit 19) of IBS Execution Control Register (IbsOpCtl,
200  * MSRC001_1033) is used to select either cycle or micro-ops counting
201  * mode.
202  */
203 static int core_pmu_ibs_config(struct perf_event *event, u64 *config)
204 {
205         switch (event->attr.type) {
206         case PERF_TYPE_HARDWARE:
207                 switch (event->attr.config) {
208                 case PERF_COUNT_HW_CPU_CYCLES:
209                         *config = 0;
210                         return 0;
211                 }
212                 break;
213         case PERF_TYPE_RAW:
214                 switch (event->attr.config) {
215                 case 0x0076:
216                         *config = 0;
217                         return 0;
218                 case 0x00C1:
219                         *config = IBS_OP_CNT_CTL;
220                         return 0;
221                 }
222                 break;
223         default:
224                 return -ENOENT;
225         }
226
227         return -EOPNOTSUPP;
228 }
229
230 /*
231  * The rip of IBS samples has skid 0. Thus, IBS supports precise
232  * levels 1 and 2 and the PERF_EFLAGS_EXACT is set. In rare cases the
233  * rip is invalid when IBS was not able to record the rip correctly.
234  * We clear PERF_EFLAGS_EXACT and take the rip from pt_regs then.
235  */
236 int forward_event_to_ibs(struct perf_event *event)
237 {
238         u64 config = 0;
239
240         if (!event->attr.precise_ip || event->attr.precise_ip > 2)
241                 return -EOPNOTSUPP;
242
243         if (!core_pmu_ibs_config(event, &config)) {
244                 event->attr.type = perf_ibs_op.pmu.type;
245                 event->attr.config = config;
246         }
247         return -ENOENT;
248 }
249
250 static int perf_ibs_init(struct perf_event *event)
251 {
252         struct hw_perf_event *hwc = &event->hw;
253         struct perf_ibs *perf_ibs;
254         u64 max_cnt, config;
255
256         perf_ibs = get_ibs_pmu(event->attr.type);
257         if (!perf_ibs)
258                 return -ENOENT;
259
260         config = event->attr.config;
261
262         if (event->pmu != &perf_ibs->pmu)
263                 return -ENOENT;
264
265         if (config & ~perf_ibs->config_mask)
266                 return -EINVAL;
267
268         if (hwc->sample_period) {
269                 if (config & perf_ibs->cnt_mask)
270                         /* raw max_cnt may not be set */
271                         return -EINVAL;
272                 if (!event->attr.sample_freq && hwc->sample_period & 0x0f)
273                         /*
274                          * lower 4 bits can not be set in ibs max cnt,
275                          * but allowing it in case we adjust the
276                          * sample period to set a frequency.
277                          */
278                         return -EINVAL;
279                 hwc->sample_period &= ~0x0FULL;
280                 if (!hwc->sample_period)
281                         hwc->sample_period = 0x10;
282         } else {
283                 max_cnt = config & perf_ibs->cnt_mask;
284                 config &= ~perf_ibs->cnt_mask;
285                 event->attr.sample_period = max_cnt << 4;
286                 hwc->sample_period = event->attr.sample_period;
287         }
288
289         if (!hwc->sample_period)
290                 return -EINVAL;
291
292         /*
293          * If we modify hwc->sample_period, we also need to update
294          * hwc->last_period and hwc->period_left.
295          */
296         hwc->last_period = hwc->sample_period;
297         local64_set(&hwc->period_left, hwc->sample_period);
298
299         hwc->config_base = perf_ibs->msr;
300         hwc->config = config;
301
302         return 0;
303 }
304
305 static int perf_ibs_set_period(struct perf_ibs *perf_ibs,
306                                struct hw_perf_event *hwc, u64 *period)
307 {
308         int overflow;
309
310         /* ignore lower 4 bits in min count: */
311         overflow = perf_event_set_period(hwc, 1<<4, perf_ibs->max_period, period);
312         local64_set(&hwc->prev_count, 0);
313
314         return overflow;
315 }
316
317 static u64 get_ibs_fetch_count(u64 config)
318 {
319         union ibs_fetch_ctl fetch_ctl = (union ibs_fetch_ctl)config;
320
321         return fetch_ctl.fetch_cnt << 4;
322 }
323
324 static u64 get_ibs_op_count(u64 config)
325 {
326         union ibs_op_ctl op_ctl = (union ibs_op_ctl)config;
327         u64 count = 0;
328
329         /*
330          * If the internal 27-bit counter rolled over, the count is MaxCnt
331          * and the lower 7 bits of CurCnt are randomized.
332          * Otherwise CurCnt has the full 27-bit current counter value.
333          */
334         if (op_ctl.op_val) {
335                 count = op_ctl.opmaxcnt << 4;
336                 if (ibs_caps & IBS_CAPS_OPCNTEXT)
337                         count += op_ctl.opmaxcnt_ext << 20;
338         } else if (ibs_caps & IBS_CAPS_RDWROPCNT) {
339                 count = op_ctl.opcurcnt;
340         }
341
342         return count;
343 }
344
345 static void
346 perf_ibs_event_update(struct perf_ibs *perf_ibs, struct perf_event *event,
347                       u64 *config)
348 {
349         u64 count = perf_ibs->get_count(*config);
350
351         /*
352          * Set width to 64 since we do not overflow on max width but
353          * instead on max count. In perf_ibs_set_period() we clear
354          * prev count manually on overflow.
355          */
356         while (!perf_event_try_update(event, count, 64)) {
357                 rdmsrl(event->hw.config_base, *config);
358                 count = perf_ibs->get_count(*config);
359         }
360 }
361
362 static inline void perf_ibs_enable_event(struct perf_ibs *perf_ibs,
363                                          struct hw_perf_event *hwc, u64 config)
364 {
365         u64 tmp = hwc->config | config;
366
367         if (perf_ibs->fetch_count_reset_broken)
368                 wrmsrl(hwc->config_base, tmp & ~perf_ibs->enable_mask);
369
370         wrmsrl(hwc->config_base, tmp | perf_ibs->enable_mask);
371 }
372
373 /*
374  * Erratum #420 Instruction-Based Sampling Engine May Generate
375  * Interrupt that Cannot Be Cleared:
376  *
377  * Must clear counter mask first, then clear the enable bit. See
378  * Revision Guide for AMD Family 10h Processors, Publication #41322.
379  */
380 static inline void perf_ibs_disable_event(struct perf_ibs *perf_ibs,
381                                           struct hw_perf_event *hwc, u64 config)
382 {
383         config &= ~perf_ibs->cnt_mask;
384         if (boot_cpu_data.x86 == 0x10)
385                 wrmsrl(hwc->config_base, config);
386         config &= ~perf_ibs->enable_mask;
387         wrmsrl(hwc->config_base, config);
388 }
389
390 /*
391  * We cannot restore the ibs pmu state, so we always needs to update
392  * the event while stopping it and then reset the state when starting
393  * again. Thus, ignoring PERF_EF_RELOAD and PERF_EF_UPDATE flags in
394  * perf_ibs_start()/perf_ibs_stop() and instead always do it.
395  */
396 static void perf_ibs_start(struct perf_event *event, int flags)
397 {
398         struct hw_perf_event *hwc = &event->hw;
399         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
400         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
401         u64 period, config = 0;
402
403         if (WARN_ON_ONCE(!(hwc->state & PERF_HES_STOPPED)))
404                 return;
405
406         WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE));
407         hwc->state = 0;
408
409         perf_ibs_set_period(perf_ibs, hwc, &period);
410         if (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_OPCNTEXT)) {
411                 config |= period & IBS_OP_MAX_CNT_EXT_MASK;
412                 period &= ~IBS_OP_MAX_CNT_EXT_MASK;
413         }
414         config |= period >> 4;
415
416         /*
417          * Set STARTED before enabling the hardware, such that a subsequent NMI
418          * must observe it.
419          */
420         set_bit(IBS_STARTED,    pcpu->state);
421         clear_bit(IBS_STOPPING, pcpu->state);
422         perf_ibs_enable_event(perf_ibs, hwc, config);
423
424         perf_event_update_userpage(event);
425 }
426
427 static void perf_ibs_stop(struct perf_event *event, int flags)
428 {
429         struct hw_perf_event *hwc = &event->hw;
430         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
431         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
432         u64 config;
433         int stopping;
434
435         if (test_and_set_bit(IBS_STOPPING, pcpu->state))
436                 return;
437
438         stopping = test_bit(IBS_STARTED, pcpu->state);
439
440         if (!stopping && (hwc->state & PERF_HES_UPTODATE))
441                 return;
442
443         rdmsrl(hwc->config_base, config);
444
445         if (stopping) {
446                 /*
447                  * Set STOPPED before disabling the hardware, such that it
448                  * must be visible to NMIs the moment we clear the EN bit,
449                  * at which point we can generate an !VALID sample which
450                  * we need to consume.
451                  */
452                 set_bit(IBS_STOPPED, pcpu->state);
453                 perf_ibs_disable_event(perf_ibs, hwc, config);
454                 /*
455                  * Clear STARTED after disabling the hardware; if it were
456                  * cleared before an NMI hitting after the clear but before
457                  * clearing the EN bit might think it a spurious NMI and not
458                  * handle it.
459                  *
460                  * Clearing it after, however, creates the problem of the NMI
461                  * handler seeing STARTED but not having a valid sample.
462                  */
463                 clear_bit(IBS_STARTED, pcpu->state);
464                 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
465                 hwc->state |= PERF_HES_STOPPED;
466         }
467
468         if (hwc->state & PERF_HES_UPTODATE)
469                 return;
470
471         /*
472          * Clear valid bit to not count rollovers on update, rollovers
473          * are only updated in the irq handler.
474          */
475         config &= ~perf_ibs->valid_mask;
476
477         perf_ibs_event_update(perf_ibs, event, &config);
478         hwc->state |= PERF_HES_UPTODATE;
479 }
480
481 static int perf_ibs_add(struct perf_event *event, int flags)
482 {
483         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
484         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
485
486         if (test_and_set_bit(IBS_ENABLED, pcpu->state))
487                 return -ENOSPC;
488
489         event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
490
491         pcpu->event = event;
492
493         if (flags & PERF_EF_START)
494                 perf_ibs_start(event, PERF_EF_RELOAD);
495
496         return 0;
497 }
498
499 static void perf_ibs_del(struct perf_event *event, int flags)
500 {
501         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
502         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
503
504         if (!test_and_clear_bit(IBS_ENABLED, pcpu->state))
505                 return;
506
507         perf_ibs_stop(event, PERF_EF_UPDATE);
508
509         pcpu->event = NULL;
510
511         perf_event_update_userpage(event);
512 }
513
514 static void perf_ibs_read(struct perf_event *event) { }
515
516 /*
517  * We need to initialize with empty group if all attributes in the
518  * group are dynamic.
519  */
520 static struct attribute *attrs_empty[] = {
521         NULL,
522 };
523
524 static struct attribute_group empty_format_group = {
525         .name = "format",
526         .attrs = attrs_empty,
527 };
528
529 static struct attribute_group empty_caps_group = {
530         .name = "caps",
531         .attrs = attrs_empty,
532 };
533
534 static const struct attribute_group *empty_attr_groups[] = {
535         &empty_format_group,
536         &empty_caps_group,
537         NULL,
538 };
539
540 PMU_FORMAT_ATTR(rand_en,        "config:57");
541 PMU_FORMAT_ATTR(cnt_ctl,        "config:19");
542 PMU_EVENT_ATTR_STRING(l3missonly, fetch_l3missonly, "config:59");
543 PMU_EVENT_ATTR_STRING(l3missonly, op_l3missonly, "config:16");
544 PMU_EVENT_ATTR_STRING(zen4_ibs_extensions, zen4_ibs_extensions, "1");
545
546 static umode_t
547 zen4_ibs_extensions_is_visible(struct kobject *kobj, struct attribute *attr, int i)
548 {
549         return ibs_caps & IBS_CAPS_ZEN4 ? attr->mode : 0;
550 }
551
552 static struct attribute *rand_en_attrs[] = {
553         &format_attr_rand_en.attr,
554         NULL,
555 };
556
557 static struct attribute *fetch_l3missonly_attrs[] = {
558         &fetch_l3missonly.attr.attr,
559         NULL,
560 };
561
562 static struct attribute *zen4_ibs_extensions_attrs[] = {
563         &zen4_ibs_extensions.attr.attr,
564         NULL,
565 };
566
567 static struct attribute_group group_rand_en = {
568         .name = "format",
569         .attrs = rand_en_attrs,
570 };
571
572 static struct attribute_group group_fetch_l3missonly = {
573         .name = "format",
574         .attrs = fetch_l3missonly_attrs,
575         .is_visible = zen4_ibs_extensions_is_visible,
576 };
577
578 static struct attribute_group group_zen4_ibs_extensions = {
579         .name = "caps",
580         .attrs = zen4_ibs_extensions_attrs,
581         .is_visible = zen4_ibs_extensions_is_visible,
582 };
583
584 static const struct attribute_group *fetch_attr_groups[] = {
585         &group_rand_en,
586         &empty_caps_group,
587         NULL,
588 };
589
590 static const struct attribute_group *fetch_attr_update[] = {
591         &group_fetch_l3missonly,
592         &group_zen4_ibs_extensions,
593         NULL,
594 };
595
596 static umode_t
597 cnt_ctl_is_visible(struct kobject *kobj, struct attribute *attr, int i)
598 {
599         return ibs_caps & IBS_CAPS_OPCNT ? attr->mode : 0;
600 }
601
602 static struct attribute *cnt_ctl_attrs[] = {
603         &format_attr_cnt_ctl.attr,
604         NULL,
605 };
606
607 static struct attribute *op_l3missonly_attrs[] = {
608         &op_l3missonly.attr.attr,
609         NULL,
610 };
611
612 static struct attribute_group group_cnt_ctl = {
613         .name = "format",
614         .attrs = cnt_ctl_attrs,
615         .is_visible = cnt_ctl_is_visible,
616 };
617
618 static struct attribute_group group_op_l3missonly = {
619         .name = "format",
620         .attrs = op_l3missonly_attrs,
621         .is_visible = zen4_ibs_extensions_is_visible,
622 };
623
624 static const struct attribute_group *op_attr_update[] = {
625         &group_cnt_ctl,
626         &group_op_l3missonly,
627         &group_zen4_ibs_extensions,
628         NULL,
629 };
630
631 static struct perf_ibs perf_ibs_fetch = {
632         .pmu = {
633                 .task_ctx_nr    = perf_invalid_context,
634
635                 .event_init     = perf_ibs_init,
636                 .add            = perf_ibs_add,
637                 .del            = perf_ibs_del,
638                 .start          = perf_ibs_start,
639                 .stop           = perf_ibs_stop,
640                 .read           = perf_ibs_read,
641                 .capabilities   = PERF_PMU_CAP_NO_EXCLUDE,
642         },
643         .msr                    = MSR_AMD64_IBSFETCHCTL,
644         .config_mask            = IBS_FETCH_CONFIG_MASK,
645         .cnt_mask               = IBS_FETCH_MAX_CNT,
646         .enable_mask            = IBS_FETCH_ENABLE,
647         .valid_mask             = IBS_FETCH_VAL,
648         .max_period             = IBS_FETCH_MAX_CNT << 4,
649         .offset_mask            = { MSR_AMD64_IBSFETCH_REG_MASK },
650         .offset_max             = MSR_AMD64_IBSFETCH_REG_COUNT,
651
652         .get_count              = get_ibs_fetch_count,
653 };
654
655 static struct perf_ibs perf_ibs_op = {
656         .pmu = {
657                 .task_ctx_nr    = perf_invalid_context,
658
659                 .event_init     = perf_ibs_init,
660                 .add            = perf_ibs_add,
661                 .del            = perf_ibs_del,
662                 .start          = perf_ibs_start,
663                 .stop           = perf_ibs_stop,
664                 .read           = perf_ibs_read,
665                 .capabilities   = PERF_PMU_CAP_NO_EXCLUDE,
666         },
667         .msr                    = MSR_AMD64_IBSOPCTL,
668         .config_mask            = IBS_OP_CONFIG_MASK,
669         .cnt_mask               = IBS_OP_MAX_CNT | IBS_OP_CUR_CNT |
670                                   IBS_OP_CUR_CNT_RAND,
671         .enable_mask            = IBS_OP_ENABLE,
672         .valid_mask             = IBS_OP_VAL,
673         .max_period             = IBS_OP_MAX_CNT << 4,
674         .offset_mask            = { MSR_AMD64_IBSOP_REG_MASK },
675         .offset_max             = MSR_AMD64_IBSOP_REG_COUNT,
676
677         .get_count              = get_ibs_op_count,
678 };
679
680 static void perf_ibs_get_mem_op(union ibs_op_data3 *op_data3,
681                                 struct perf_sample_data *data)
682 {
683         union perf_mem_data_src *data_src = &data->data_src;
684
685         data_src->mem_op = PERF_MEM_OP_NA;
686
687         if (op_data3->ld_op)
688                 data_src->mem_op = PERF_MEM_OP_LOAD;
689         else if (op_data3->st_op)
690                 data_src->mem_op = PERF_MEM_OP_STORE;
691 }
692
693 /*
694  * Processors having CPUID_Fn8000001B_EAX[11] aka IBS_CAPS_ZEN4 has
695  * more fine granular DataSrc encodings. Others have coarse.
696  */
697 static u8 perf_ibs_data_src(union ibs_op_data2 *op_data2)
698 {
699         if (ibs_caps & IBS_CAPS_ZEN4)
700                 return (op_data2->data_src_hi << 3) | op_data2->data_src_lo;
701
702         return op_data2->data_src_lo;
703 }
704
705 static void perf_ibs_get_mem_lvl(union ibs_op_data2 *op_data2,
706                                  union ibs_op_data3 *op_data3,
707                                  struct perf_sample_data *data)
708 {
709         union perf_mem_data_src *data_src = &data->data_src;
710         u8 ibs_data_src = perf_ibs_data_src(op_data2);
711
712         data_src->mem_lvl = 0;
713
714         /*
715          * DcMiss, L2Miss, DataSrc, DcMissLat etc. are all invalid for Uncached
716          * memory accesses. So, check DcUcMemAcc bit early.
717          */
718         if (op_data3->dc_uc_mem_acc && ibs_data_src != IBS_DATA_SRC_EXT_IO) {
719                 data_src->mem_lvl = PERF_MEM_LVL_UNC | PERF_MEM_LVL_HIT;
720                 return;
721         }
722
723         /* L1 Hit */
724         if (op_data3->dc_miss == 0) {
725                 data_src->mem_lvl = PERF_MEM_LVL_L1 | PERF_MEM_LVL_HIT;
726                 return;
727         }
728
729         /* L2 Hit */
730         if (op_data3->l2_miss == 0) {
731                 /* Erratum #1293 */
732                 if (boot_cpu_data.x86 != 0x19 || boot_cpu_data.x86_model > 0xF ||
733                     !(op_data3->sw_pf || op_data3->dc_miss_no_mab_alloc)) {
734                         data_src->mem_lvl = PERF_MEM_LVL_L2 | PERF_MEM_LVL_HIT;
735                         return;
736                 }
737         }
738
739         /*
740          * OP_DATA2 is valid only for load ops. Skip all checks which
741          * uses OP_DATA2[DataSrc].
742          */
743         if (data_src->mem_op != PERF_MEM_OP_LOAD)
744                 goto check_mab;
745
746         /* L3 Hit */
747         if (ibs_caps & IBS_CAPS_ZEN4) {
748                 if (ibs_data_src == IBS_DATA_SRC_EXT_LOC_CACHE) {
749                         data_src->mem_lvl = PERF_MEM_LVL_L3 | PERF_MEM_LVL_HIT;
750                         return;
751                 }
752         } else {
753                 if (ibs_data_src == IBS_DATA_SRC_LOC_CACHE) {
754                         data_src->mem_lvl = PERF_MEM_LVL_L3 | PERF_MEM_LVL_REM_CCE1 |
755                                             PERF_MEM_LVL_HIT;
756                         return;
757                 }
758         }
759
760         /* A peer cache in a near CCX */
761         if (ibs_caps & IBS_CAPS_ZEN4 &&
762             ibs_data_src == IBS_DATA_SRC_EXT_NEAR_CCX_CACHE) {
763                 data_src->mem_lvl = PERF_MEM_LVL_REM_CCE1 | PERF_MEM_LVL_HIT;
764                 return;
765         }
766
767         /* A peer cache in a far CCX */
768         if (ibs_caps & IBS_CAPS_ZEN4) {
769                 if (ibs_data_src == IBS_DATA_SRC_EXT_FAR_CCX_CACHE) {
770                         data_src->mem_lvl = PERF_MEM_LVL_REM_CCE2 | PERF_MEM_LVL_HIT;
771                         return;
772                 }
773         } else {
774                 if (ibs_data_src == IBS_DATA_SRC_REM_CACHE) {
775                         data_src->mem_lvl = PERF_MEM_LVL_REM_CCE2 | PERF_MEM_LVL_HIT;
776                         return;
777                 }
778         }
779
780         /* DRAM */
781         if (ibs_data_src == IBS_DATA_SRC_EXT_DRAM) {
782                 if (op_data2->rmt_node == 0)
783                         data_src->mem_lvl = PERF_MEM_LVL_LOC_RAM | PERF_MEM_LVL_HIT;
784                 else
785                         data_src->mem_lvl = PERF_MEM_LVL_REM_RAM1 | PERF_MEM_LVL_HIT;
786                 return;
787         }
788
789         /* PMEM */
790         if (ibs_caps & IBS_CAPS_ZEN4 && ibs_data_src == IBS_DATA_SRC_EXT_PMEM) {
791                 data_src->mem_lvl_num = PERF_MEM_LVLNUM_PMEM;
792                 if (op_data2->rmt_node) {
793                         data_src->mem_remote = PERF_MEM_REMOTE_REMOTE;
794                         /* IBS doesn't provide Remote socket detail */
795                         data_src->mem_hops = PERF_MEM_HOPS_1;
796                 }
797                 return;
798         }
799
800         /* Extension Memory */
801         if (ibs_caps & IBS_CAPS_ZEN4 &&
802             ibs_data_src == IBS_DATA_SRC_EXT_EXT_MEM) {
803                 data_src->mem_lvl_num = PERF_MEM_LVLNUM_CXL;
804                 if (op_data2->rmt_node) {
805                         data_src->mem_remote = PERF_MEM_REMOTE_REMOTE;
806                         /* IBS doesn't provide Remote socket detail */
807                         data_src->mem_hops = PERF_MEM_HOPS_1;
808                 }
809                 return;
810         }
811
812         /* IO */
813         if (ibs_data_src == IBS_DATA_SRC_EXT_IO) {
814                 data_src->mem_lvl = PERF_MEM_LVL_IO;
815                 data_src->mem_lvl_num = PERF_MEM_LVLNUM_IO;
816                 if (op_data2->rmt_node) {
817                         data_src->mem_remote = PERF_MEM_REMOTE_REMOTE;
818                         /* IBS doesn't provide Remote socket detail */
819                         data_src->mem_hops = PERF_MEM_HOPS_1;
820                 }
821                 return;
822         }
823
824 check_mab:
825         /*
826          * MAB (Miss Address Buffer) Hit. MAB keeps track of outstanding
827          * DC misses. However, such data may come from any level in mem
828          * hierarchy. IBS provides detail about both MAB as well as actual
829          * DataSrc simultaneously. Prioritize DataSrc over MAB, i.e. set
830          * MAB only when IBS fails to provide DataSrc.
831          */
832         if (op_data3->dc_miss_no_mab_alloc) {
833                 data_src->mem_lvl = PERF_MEM_LVL_LFB | PERF_MEM_LVL_HIT;
834                 return;
835         }
836
837         data_src->mem_lvl = PERF_MEM_LVL_NA;
838 }
839
840 static bool perf_ibs_cache_hit_st_valid(void)
841 {
842         /* 0: Uninitialized, 1: Valid, -1: Invalid */
843         static int cache_hit_st_valid;
844
845         if (unlikely(!cache_hit_st_valid)) {
846                 if (boot_cpu_data.x86 == 0x19 &&
847                     (boot_cpu_data.x86_model <= 0xF ||
848                     (boot_cpu_data.x86_model >= 0x20 &&
849                      boot_cpu_data.x86_model <= 0x5F))) {
850                         cache_hit_st_valid = -1;
851                 } else {
852                         cache_hit_st_valid = 1;
853                 }
854         }
855
856         return cache_hit_st_valid == 1;
857 }
858
859 static void perf_ibs_get_mem_snoop(union ibs_op_data2 *op_data2,
860                                    struct perf_sample_data *data)
861 {
862         union perf_mem_data_src *data_src = &data->data_src;
863         u8 ibs_data_src;
864
865         data_src->mem_snoop = PERF_MEM_SNOOP_NA;
866
867         if (!perf_ibs_cache_hit_st_valid() ||
868             data_src->mem_op != PERF_MEM_OP_LOAD ||
869             data_src->mem_lvl & PERF_MEM_LVL_L1 ||
870             data_src->mem_lvl & PERF_MEM_LVL_L2 ||
871             op_data2->cache_hit_st)
872                 return;
873
874         ibs_data_src = perf_ibs_data_src(op_data2);
875
876         if (ibs_caps & IBS_CAPS_ZEN4) {
877                 if (ibs_data_src == IBS_DATA_SRC_EXT_LOC_CACHE ||
878                     ibs_data_src == IBS_DATA_SRC_EXT_NEAR_CCX_CACHE ||
879                     ibs_data_src == IBS_DATA_SRC_EXT_FAR_CCX_CACHE)
880                         data_src->mem_snoop = PERF_MEM_SNOOP_HITM;
881         } else if (ibs_data_src == IBS_DATA_SRC_LOC_CACHE) {
882                 data_src->mem_snoop = PERF_MEM_SNOOP_HITM;
883         }
884 }
885
886 static void perf_ibs_get_tlb_lvl(union ibs_op_data3 *op_data3,
887                                  struct perf_sample_data *data)
888 {
889         union perf_mem_data_src *data_src = &data->data_src;
890
891         data_src->mem_dtlb = PERF_MEM_TLB_NA;
892
893         if (!op_data3->dc_lin_addr_valid)
894                 return;
895
896         if (!op_data3->dc_l1tlb_miss) {
897                 data_src->mem_dtlb = PERF_MEM_TLB_L1 | PERF_MEM_TLB_HIT;
898                 return;
899         }
900
901         if (!op_data3->dc_l2tlb_miss) {
902                 data_src->mem_dtlb = PERF_MEM_TLB_L2 | PERF_MEM_TLB_HIT;
903                 return;
904         }
905
906         data_src->mem_dtlb = PERF_MEM_TLB_L2 | PERF_MEM_TLB_MISS;
907 }
908
909 static void perf_ibs_get_mem_lock(union ibs_op_data3 *op_data3,
910                                   struct perf_sample_data *data)
911 {
912         union perf_mem_data_src *data_src = &data->data_src;
913
914         data_src->mem_lock = PERF_MEM_LOCK_NA;
915
916         if (op_data3->dc_locked_op)
917                 data_src->mem_lock = PERF_MEM_LOCK_LOCKED;
918 }
919
920 #define ibs_op_msr_idx(msr)     (msr - MSR_AMD64_IBSOPCTL)
921
922 static void perf_ibs_get_data_src(struct perf_ibs_data *ibs_data,
923                                   struct perf_sample_data *data,
924                                   union ibs_op_data2 *op_data2,
925                                   union ibs_op_data3 *op_data3)
926 {
927         perf_ibs_get_mem_lvl(op_data2, op_data3, data);
928         perf_ibs_get_mem_snoop(op_data2, data);
929         perf_ibs_get_tlb_lvl(op_data3, data);
930         perf_ibs_get_mem_lock(op_data3, data);
931 }
932
933 static __u64 perf_ibs_get_op_data2(struct perf_ibs_data *ibs_data,
934                                    union ibs_op_data3 *op_data3)
935 {
936         __u64 val = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSOPDATA2)];
937
938         /* Erratum #1293 */
939         if (boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model <= 0xF &&
940             (op_data3->sw_pf || op_data3->dc_miss_no_mab_alloc)) {
941                 /*
942                  * OP_DATA2 has only two fields on Zen3: DataSrc and RmtNode.
943                  * DataSrc=0 is 'No valid status' and RmtNode is invalid when
944                  * DataSrc=0.
945                  */
946                 val = 0;
947         }
948         return val;
949 }
950
951 static void perf_ibs_parse_ld_st_data(__u64 sample_type,
952                                       struct perf_ibs_data *ibs_data,
953                                       struct perf_sample_data *data)
954 {
955         union ibs_op_data3 op_data3;
956         union ibs_op_data2 op_data2;
957         union ibs_op_data op_data;
958
959         data->data_src.val = PERF_MEM_NA;
960         op_data3.val = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSOPDATA3)];
961
962         perf_ibs_get_mem_op(&op_data3, data);
963         if (data->data_src.mem_op != PERF_MEM_OP_LOAD &&
964             data->data_src.mem_op != PERF_MEM_OP_STORE)
965                 return;
966
967         op_data2.val = perf_ibs_get_op_data2(ibs_data, &op_data3);
968
969         if (sample_type & PERF_SAMPLE_DATA_SRC) {
970                 perf_ibs_get_data_src(ibs_data, data, &op_data2, &op_data3);
971                 data->sample_flags |= PERF_SAMPLE_DATA_SRC;
972         }
973
974         if (sample_type & PERF_SAMPLE_WEIGHT_TYPE && op_data3.dc_miss &&
975             data->data_src.mem_op == PERF_MEM_OP_LOAD) {
976                 op_data.val = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSOPDATA)];
977
978                 if (sample_type & PERF_SAMPLE_WEIGHT_STRUCT) {
979                         data->weight.var1_dw = op_data3.dc_miss_lat;
980                         data->weight.var2_w = op_data.tag_to_ret_ctr;
981                 } else if (sample_type & PERF_SAMPLE_WEIGHT) {
982                         data->weight.full = op_data3.dc_miss_lat;
983                 }
984                 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
985         }
986
987         if (sample_type & PERF_SAMPLE_ADDR && op_data3.dc_lin_addr_valid) {
988                 data->addr = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSDCLINAD)];
989                 data->sample_flags |= PERF_SAMPLE_ADDR;
990         }
991
992         if (sample_type & PERF_SAMPLE_PHYS_ADDR && op_data3.dc_phy_addr_valid) {
993                 data->phys_addr = ibs_data->regs[ibs_op_msr_idx(MSR_AMD64_IBSDCPHYSAD)];
994                 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
995         }
996 }
997
998 static int perf_ibs_get_offset_max(struct perf_ibs *perf_ibs, u64 sample_type,
999                                    int check_rip)
1000 {
1001         if (sample_type & PERF_SAMPLE_RAW ||
1002             (perf_ibs == &perf_ibs_op &&
1003              (sample_type & PERF_SAMPLE_DATA_SRC ||
1004               sample_type & PERF_SAMPLE_WEIGHT_TYPE ||
1005               sample_type & PERF_SAMPLE_ADDR ||
1006               sample_type & PERF_SAMPLE_PHYS_ADDR)))
1007                 return perf_ibs->offset_max;
1008         else if (check_rip)
1009                 return 3;
1010         return 1;
1011 }
1012
1013 static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs)
1014 {
1015         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
1016         struct perf_event *event = pcpu->event;
1017         struct hw_perf_event *hwc;
1018         struct perf_sample_data data;
1019         struct perf_raw_record raw;
1020         struct pt_regs regs;
1021         struct perf_ibs_data ibs_data;
1022         int offset, size, check_rip, offset_max, throttle = 0;
1023         unsigned int msr;
1024         u64 *buf, *config, period, new_config = 0;
1025
1026         if (!test_bit(IBS_STARTED, pcpu->state)) {
1027 fail:
1028                 /*
1029                  * Catch spurious interrupts after stopping IBS: After
1030                  * disabling IBS there could be still incoming NMIs
1031                  * with samples that even have the valid bit cleared.
1032                  * Mark all this NMIs as handled.
1033                  */
1034                 if (test_and_clear_bit(IBS_STOPPED, pcpu->state))
1035                         return 1;
1036
1037                 return 0;
1038         }
1039
1040         if (WARN_ON_ONCE(!event))
1041                 goto fail;
1042
1043         hwc = &event->hw;
1044         msr = hwc->config_base;
1045         buf = ibs_data.regs;
1046         rdmsrl(msr, *buf);
1047         if (!(*buf++ & perf_ibs->valid_mask))
1048                 goto fail;
1049
1050         config = &ibs_data.regs[0];
1051         perf_ibs_event_update(perf_ibs, event, config);
1052         perf_sample_data_init(&data, 0, hwc->last_period);
1053         if (!perf_ibs_set_period(perf_ibs, hwc, &period))
1054                 goto out;       /* no sw counter overflow */
1055
1056         ibs_data.caps = ibs_caps;
1057         size = 1;
1058         offset = 1;
1059         check_rip = (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_RIPINVALIDCHK));
1060
1061         offset_max = perf_ibs_get_offset_max(perf_ibs, event->attr.sample_type, check_rip);
1062
1063         do {
1064                 rdmsrl(msr + offset, *buf++);
1065                 size++;
1066                 offset = find_next_bit(perf_ibs->offset_mask,
1067                                        perf_ibs->offset_max,
1068                                        offset + 1);
1069         } while (offset < offset_max);
1070         /*
1071          * Read IbsBrTarget, IbsOpData4, and IbsExtdCtl separately
1072          * depending on their availability.
1073          * Can't add to offset_max as they are staggered
1074          */
1075         if (event->attr.sample_type & PERF_SAMPLE_RAW) {
1076                 if (perf_ibs == &perf_ibs_op) {
1077                         if (ibs_caps & IBS_CAPS_BRNTRGT) {
1078                                 rdmsrl(MSR_AMD64_IBSBRTARGET, *buf++);
1079                                 size++;
1080                         }
1081                         if (ibs_caps & IBS_CAPS_OPDATA4) {
1082                                 rdmsrl(MSR_AMD64_IBSOPDATA4, *buf++);
1083                                 size++;
1084                         }
1085                 }
1086                 if (perf_ibs == &perf_ibs_fetch && (ibs_caps & IBS_CAPS_FETCHCTLEXTD)) {
1087                         rdmsrl(MSR_AMD64_ICIBSEXTDCTL, *buf++);
1088                         size++;
1089                 }
1090         }
1091         ibs_data.size = sizeof(u64) * size;
1092
1093         regs = *iregs;
1094         if (check_rip && (ibs_data.regs[2] & IBS_RIP_INVALID)) {
1095                 regs.flags &= ~PERF_EFLAGS_EXACT;
1096         } else {
1097                 /* Workaround for erratum #1197 */
1098                 if (perf_ibs->fetch_ignore_if_zero_rip && !(ibs_data.regs[1]))
1099                         goto out;
1100
1101                 set_linear_ip(&regs, ibs_data.regs[1]);
1102                 regs.flags |= PERF_EFLAGS_EXACT;
1103         }
1104
1105         if (event->attr.sample_type & PERF_SAMPLE_RAW) {
1106                 raw = (struct perf_raw_record){
1107                         .frag = {
1108                                 .size = sizeof(u32) + ibs_data.size,
1109                                 .data = ibs_data.data,
1110                         },
1111                 };
1112                 data.raw = &raw;
1113                 data.sample_flags |= PERF_SAMPLE_RAW;
1114         }
1115
1116         if (perf_ibs == &perf_ibs_op)
1117                 perf_ibs_parse_ld_st_data(event->attr.sample_type, &ibs_data, &data);
1118
1119         /*
1120          * rip recorded by IbsOpRip will not be consistent with rsp and rbp
1121          * recorded as part of interrupt regs. Thus we need to use rip from
1122          * interrupt regs while unwinding call stack.
1123          */
1124         if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
1125                 data.callchain = perf_callchain(event, iregs);
1126                 data.sample_flags |= PERF_SAMPLE_CALLCHAIN;
1127         }
1128
1129         throttle = perf_event_overflow(event, &data, &regs);
1130 out:
1131         if (throttle) {
1132                 perf_ibs_stop(event, 0);
1133         } else {
1134                 if (perf_ibs == &perf_ibs_op) {
1135                         if (ibs_caps & IBS_CAPS_OPCNTEXT) {
1136                                 new_config = period & IBS_OP_MAX_CNT_EXT_MASK;
1137                                 period &= ~IBS_OP_MAX_CNT_EXT_MASK;
1138                         }
1139                         if ((ibs_caps & IBS_CAPS_RDWROPCNT) && (*config & IBS_OP_CNT_CTL))
1140                                 new_config |= *config & IBS_OP_CUR_CNT_RAND;
1141                 }
1142                 new_config |= period >> 4;
1143
1144                 perf_ibs_enable_event(perf_ibs, hwc, new_config);
1145         }
1146
1147         perf_event_update_userpage(event);
1148
1149         return 1;
1150 }
1151
1152 static int
1153 perf_ibs_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1154 {
1155         u64 stamp = sched_clock();
1156         int handled = 0;
1157
1158         handled += perf_ibs_handle_irq(&perf_ibs_fetch, regs);
1159         handled += perf_ibs_handle_irq(&perf_ibs_op, regs);
1160
1161         if (handled)
1162                 inc_irq_stat(apic_perf_irqs);
1163
1164         perf_sample_event_took(sched_clock() - stamp);
1165
1166         return handled;
1167 }
1168 NOKPROBE_SYMBOL(perf_ibs_nmi_handler);
1169
1170 static __init int perf_ibs_pmu_init(struct perf_ibs *perf_ibs, char *name)
1171 {
1172         struct cpu_perf_ibs __percpu *pcpu;
1173         int ret;
1174
1175         pcpu = alloc_percpu(struct cpu_perf_ibs);
1176         if (!pcpu)
1177                 return -ENOMEM;
1178
1179         perf_ibs->pcpu = pcpu;
1180
1181         ret = perf_pmu_register(&perf_ibs->pmu, name, -1);
1182         if (ret) {
1183                 perf_ibs->pcpu = NULL;
1184                 free_percpu(pcpu);
1185         }
1186
1187         return ret;
1188 }
1189
1190 static __init int perf_ibs_fetch_init(void)
1191 {
1192         /*
1193          * Some chips fail to reset the fetch count when it is written; instead
1194          * they need a 0-1 transition of IbsFetchEn.
1195          */
1196         if (boot_cpu_data.x86 >= 0x16 && boot_cpu_data.x86 <= 0x18)
1197                 perf_ibs_fetch.fetch_count_reset_broken = 1;
1198
1199         if (boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model < 0x10)
1200                 perf_ibs_fetch.fetch_ignore_if_zero_rip = 1;
1201
1202         if (ibs_caps & IBS_CAPS_ZEN4)
1203                 perf_ibs_fetch.config_mask |= IBS_FETCH_L3MISSONLY;
1204
1205         perf_ibs_fetch.pmu.attr_groups = fetch_attr_groups;
1206         perf_ibs_fetch.pmu.attr_update = fetch_attr_update;
1207
1208         return perf_ibs_pmu_init(&perf_ibs_fetch, "ibs_fetch");
1209 }
1210
1211 static __init int perf_ibs_op_init(void)
1212 {
1213         if (ibs_caps & IBS_CAPS_OPCNT)
1214                 perf_ibs_op.config_mask |= IBS_OP_CNT_CTL;
1215
1216         if (ibs_caps & IBS_CAPS_OPCNTEXT) {
1217                 perf_ibs_op.max_period  |= IBS_OP_MAX_CNT_EXT_MASK;
1218                 perf_ibs_op.config_mask |= IBS_OP_MAX_CNT_EXT_MASK;
1219                 perf_ibs_op.cnt_mask    |= IBS_OP_MAX_CNT_EXT_MASK;
1220         }
1221
1222         if (ibs_caps & IBS_CAPS_ZEN4)
1223                 perf_ibs_op.config_mask |= IBS_OP_L3MISSONLY;
1224
1225         perf_ibs_op.pmu.attr_groups = empty_attr_groups;
1226         perf_ibs_op.pmu.attr_update = op_attr_update;
1227
1228         return perf_ibs_pmu_init(&perf_ibs_op, "ibs_op");
1229 }
1230
1231 static __init int perf_event_ibs_init(void)
1232 {
1233         int ret;
1234
1235         ret = perf_ibs_fetch_init();
1236         if (ret)
1237                 return ret;
1238
1239         ret = perf_ibs_op_init();
1240         if (ret)
1241                 goto err_op;
1242
1243         ret = register_nmi_handler(NMI_LOCAL, perf_ibs_nmi_handler, 0, "perf_ibs");
1244         if (ret)
1245                 goto err_nmi;
1246
1247         pr_info("perf: AMD IBS detected (0x%08x)\n", ibs_caps);
1248         return 0;
1249
1250 err_nmi:
1251         perf_pmu_unregister(&perf_ibs_op.pmu);
1252         free_percpu(perf_ibs_op.pcpu);
1253         perf_ibs_op.pcpu = NULL;
1254 err_op:
1255         perf_pmu_unregister(&perf_ibs_fetch.pmu);
1256         free_percpu(perf_ibs_fetch.pcpu);
1257         perf_ibs_fetch.pcpu = NULL;
1258
1259         return ret;
1260 }
1261
1262 #else /* defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_AMD) */
1263
1264 static __init int perf_event_ibs_init(void)
1265 {
1266         return 0;
1267 }
1268
1269 #endif
1270
1271 /* IBS - apic initialization, for perf and oprofile */
1272
1273 static __init u32 __get_ibs_caps(void)
1274 {
1275         u32 caps;
1276         unsigned int max_level;
1277
1278         if (!boot_cpu_has(X86_FEATURE_IBS))
1279                 return 0;
1280
1281         /* check IBS cpuid feature flags */
1282         max_level = cpuid_eax(0x80000000);
1283         if (max_level < IBS_CPUID_FEATURES)
1284                 return IBS_CAPS_DEFAULT;
1285
1286         caps = cpuid_eax(IBS_CPUID_FEATURES);
1287         if (!(caps & IBS_CAPS_AVAIL))
1288                 /* cpuid flags not valid */
1289                 return IBS_CAPS_DEFAULT;
1290
1291         return caps;
1292 }
1293
1294 u32 get_ibs_caps(void)
1295 {
1296         return ibs_caps;
1297 }
1298
1299 EXPORT_SYMBOL(get_ibs_caps);
1300
1301 static inline int get_eilvt(int offset)
1302 {
1303         return !setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 1);
1304 }
1305
1306 static inline int put_eilvt(int offset)
1307 {
1308         return !setup_APIC_eilvt(offset, 0, 0, 1);
1309 }
1310
1311 /*
1312  * Check and reserve APIC extended interrupt LVT offset for IBS if available.
1313  */
1314 static inline int ibs_eilvt_valid(void)
1315 {
1316         int offset;
1317         u64 val;
1318         int valid = 0;
1319
1320         preempt_disable();
1321
1322         rdmsrl(MSR_AMD64_IBSCTL, val);
1323         offset = val & IBSCTL_LVT_OFFSET_MASK;
1324
1325         if (!(val & IBSCTL_LVT_OFFSET_VALID)) {
1326                 pr_err(FW_BUG "cpu %d, invalid IBS interrupt offset %d (MSR%08X=0x%016llx)\n",
1327                        smp_processor_id(), offset, MSR_AMD64_IBSCTL, val);
1328                 goto out;
1329         }
1330
1331         if (!get_eilvt(offset)) {
1332                 pr_err(FW_BUG "cpu %d, IBS interrupt offset %d not available (MSR%08X=0x%016llx)\n",
1333                        smp_processor_id(), offset, MSR_AMD64_IBSCTL, val);
1334                 goto out;
1335         }
1336
1337         valid = 1;
1338 out:
1339         preempt_enable();
1340
1341         return valid;
1342 }
1343
1344 static int setup_ibs_ctl(int ibs_eilvt_off)
1345 {
1346         struct pci_dev *cpu_cfg;
1347         int nodes;
1348         u32 value = 0;
1349
1350         nodes = 0;
1351         cpu_cfg = NULL;
1352         do {
1353                 cpu_cfg = pci_get_device(PCI_VENDOR_ID_AMD,
1354                                          PCI_DEVICE_ID_AMD_10H_NB_MISC,
1355                                          cpu_cfg);
1356                 if (!cpu_cfg)
1357                         break;
1358                 ++nodes;
1359                 pci_write_config_dword(cpu_cfg, IBSCTL, ibs_eilvt_off
1360                                        | IBSCTL_LVT_OFFSET_VALID);
1361                 pci_read_config_dword(cpu_cfg, IBSCTL, &value);
1362                 if (value != (ibs_eilvt_off | IBSCTL_LVT_OFFSET_VALID)) {
1363                         pci_dev_put(cpu_cfg);
1364                         pr_debug("Failed to setup IBS LVT offset, IBSCTL = 0x%08x\n",
1365                                  value);
1366                         return -EINVAL;
1367                 }
1368         } while (1);
1369
1370         if (!nodes) {
1371                 pr_debug("No CPU node configured for IBS\n");
1372                 return -ENODEV;
1373         }
1374
1375         return 0;
1376 }
1377
1378 /*
1379  * This runs only on the current cpu. We try to find an LVT offset and
1380  * setup the local APIC. For this we must disable preemption. On
1381  * success we initialize all nodes with this offset. This updates then
1382  * the offset in the IBS_CTL per-node msr. The per-core APIC setup of
1383  * the IBS interrupt vector is handled by perf_ibs_cpu_notifier that
1384  * is using the new offset.
1385  */
1386 static void force_ibs_eilvt_setup(void)
1387 {
1388         int offset;
1389         int ret;
1390
1391         preempt_disable();
1392         /* find the next free available EILVT entry, skip offset 0 */
1393         for (offset = 1; offset < APIC_EILVT_NR_MAX; offset++) {
1394                 if (get_eilvt(offset))
1395                         break;
1396         }
1397         preempt_enable();
1398
1399         if (offset == APIC_EILVT_NR_MAX) {
1400                 pr_debug("No EILVT entry available\n");
1401                 return;
1402         }
1403
1404         ret = setup_ibs_ctl(offset);
1405         if (ret)
1406                 goto out;
1407
1408         if (!ibs_eilvt_valid())
1409                 goto out;
1410
1411         pr_info("LVT offset %d assigned\n", offset);
1412
1413         return;
1414 out:
1415         preempt_disable();
1416         put_eilvt(offset);
1417         preempt_enable();
1418         return;
1419 }
1420
1421 static void ibs_eilvt_setup(void)
1422 {
1423         /*
1424          * Force LVT offset assignment for family 10h: The offsets are
1425          * not assigned by the BIOS for this family, so the OS is
1426          * responsible for doing it. If the OS assignment fails, fall
1427          * back to BIOS settings and try to setup this.
1428          */
1429         if (boot_cpu_data.x86 == 0x10)
1430                 force_ibs_eilvt_setup();
1431 }
1432
1433 static inline int get_ibs_lvt_offset(void)
1434 {
1435         u64 val;
1436
1437         rdmsrl(MSR_AMD64_IBSCTL, val);
1438         if (!(val & IBSCTL_LVT_OFFSET_VALID))
1439                 return -EINVAL;
1440
1441         return val & IBSCTL_LVT_OFFSET_MASK;
1442 }
1443
1444 static void setup_APIC_ibs(void)
1445 {
1446         int offset;
1447
1448         offset = get_ibs_lvt_offset();
1449         if (offset < 0)
1450                 goto failed;
1451
1452         if (!setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 0))
1453                 return;
1454 failed:
1455         pr_warn("perf: IBS APIC setup failed on cpu #%d\n",
1456                 smp_processor_id());
1457 }
1458
1459 static void clear_APIC_ibs(void)
1460 {
1461         int offset;
1462
1463         offset = get_ibs_lvt_offset();
1464         if (offset >= 0)
1465                 setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_FIX, 1);
1466 }
1467
1468 static int x86_pmu_amd_ibs_starting_cpu(unsigned int cpu)
1469 {
1470         setup_APIC_ibs();
1471         return 0;
1472 }
1473
1474 #ifdef CONFIG_PM
1475
1476 static int perf_ibs_suspend(void)
1477 {
1478         clear_APIC_ibs();
1479         return 0;
1480 }
1481
1482 static void perf_ibs_resume(void)
1483 {
1484         ibs_eilvt_setup();
1485         setup_APIC_ibs();
1486 }
1487
1488 static struct syscore_ops perf_ibs_syscore_ops = {
1489         .resume         = perf_ibs_resume,
1490         .suspend        = perf_ibs_suspend,
1491 };
1492
1493 static void perf_ibs_pm_init(void)
1494 {
1495         register_syscore_ops(&perf_ibs_syscore_ops);
1496 }
1497
1498 #else
1499
1500 static inline void perf_ibs_pm_init(void) { }
1501
1502 #endif
1503
1504 static int x86_pmu_amd_ibs_dying_cpu(unsigned int cpu)
1505 {
1506         clear_APIC_ibs();
1507         return 0;
1508 }
1509
1510 static __init int amd_ibs_init(void)
1511 {
1512         u32 caps;
1513
1514         caps = __get_ibs_caps();
1515         if (!caps)
1516                 return -ENODEV; /* ibs not supported by the cpu */
1517
1518         ibs_eilvt_setup();
1519
1520         if (!ibs_eilvt_valid())
1521                 return -EINVAL;
1522
1523         perf_ibs_pm_init();
1524
1525         ibs_caps = caps;
1526         /* make ibs_caps visible to other cpus: */
1527         smp_mb();
1528         /*
1529          * x86_pmu_amd_ibs_starting_cpu will be called from core on
1530          * all online cpus.
1531          */
1532         cpuhp_setup_state(CPUHP_AP_PERF_X86_AMD_IBS_STARTING,
1533                           "perf/x86/amd/ibs:starting",
1534                           x86_pmu_amd_ibs_starting_cpu,
1535                           x86_pmu_amd_ibs_dying_cpu);
1536
1537         return perf_event_ibs_init();
1538 }
1539
1540 /* Since we need the pci subsystem to init ibs we can't do this earlier: */
1541 device_initcall(amd_ibs_init);