GNU Linux-libre 5.15.137-gnu
[releases.git] / arch / 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         struct attribute                **format_attrs;
98         struct attribute_group          format_group;
99         const struct attribute_group    *attr_groups[2];
100
101         u64                             (*get_count)(u64 config);
102 };
103
104 static int
105 perf_event_set_period(struct hw_perf_event *hwc, u64 min, u64 max, u64 *hw_period)
106 {
107         s64 left = local64_read(&hwc->period_left);
108         s64 period = hwc->sample_period;
109         int overflow = 0;
110
111         /*
112          * If we are way outside a reasonable range then just skip forward:
113          */
114         if (unlikely(left <= -period)) {
115                 left = period;
116                 local64_set(&hwc->period_left, left);
117                 hwc->last_period = period;
118                 overflow = 1;
119         }
120
121         if (unlikely(left < (s64)min)) {
122                 left += period;
123                 local64_set(&hwc->period_left, left);
124                 hwc->last_period = period;
125                 overflow = 1;
126         }
127
128         /*
129          * If the hw period that triggers the sw overflow is too short
130          * we might hit the irq handler. This biases the results.
131          * Thus we shorten the next-to-last period and set the last
132          * period to the max period.
133          */
134         if (left > max) {
135                 left -= max;
136                 if (left > max)
137                         left = max;
138                 else if (left < min)
139                         left = min;
140         }
141
142         *hw_period = (u64)left;
143
144         return overflow;
145 }
146
147 static  int
148 perf_event_try_update(struct perf_event *event, u64 new_raw_count, int width)
149 {
150         struct hw_perf_event *hwc = &event->hw;
151         int shift = 64 - width;
152         u64 prev_raw_count;
153         u64 delta;
154
155         /*
156          * Careful: an NMI might modify the previous event value.
157          *
158          * Our tactic to handle this is to first atomically read and
159          * exchange a new raw count - then add that new-prev delta
160          * count to the generic event atomically:
161          */
162         prev_raw_count = local64_read(&hwc->prev_count);
163         if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
164                                         new_raw_count) != prev_raw_count)
165                 return 0;
166
167         /*
168          * Now we have the new raw value and have updated the prev
169          * timestamp already. We can now calculate the elapsed delta
170          * (event-)time and add that to the generic event.
171          *
172          * Careful, not all hw sign-extends above the physical width
173          * of the count.
174          */
175         delta = (new_raw_count << shift) - (prev_raw_count << shift);
176         delta >>= shift;
177
178         local64_add(delta, &event->count);
179         local64_sub(delta, &hwc->period_left);
180
181         return 1;
182 }
183
184 static struct perf_ibs perf_ibs_fetch;
185 static struct perf_ibs perf_ibs_op;
186
187 static struct perf_ibs *get_ibs_pmu(int type)
188 {
189         if (perf_ibs_fetch.pmu.type == type)
190                 return &perf_ibs_fetch;
191         if (perf_ibs_op.pmu.type == type)
192                 return &perf_ibs_op;
193         return NULL;
194 }
195
196 /*
197  * core pmu config -> IBS config
198  *
199  *  perf record -a -e cpu-cycles:p ...    # use ibs op counting cycle count
200  *  perf record -a -e r076:p ...          # same as -e cpu-cycles:p
201  *  perf record -a -e r0C1:p ...          # use ibs op counting micro-ops
202  *
203  * IbsOpCntCtl (bit 19) of IBS Execution Control Register (IbsOpCtl,
204  * MSRC001_1033) is used to select either cycle or micro-ops counting
205  * mode.
206  */
207 static int core_pmu_ibs_config(struct perf_event *event, u64 *config)
208 {
209         switch (event->attr.type) {
210         case PERF_TYPE_HARDWARE:
211                 switch (event->attr.config) {
212                 case PERF_COUNT_HW_CPU_CYCLES:
213                         *config = 0;
214                         return 0;
215                 }
216                 break;
217         case PERF_TYPE_RAW:
218                 switch (event->attr.config) {
219                 case 0x0076:
220                         *config = 0;
221                         return 0;
222                 case 0x00C1:
223                         *config = IBS_OP_CNT_CTL;
224                         return 0;
225                 }
226                 break;
227         default:
228                 return -ENOENT;
229         }
230
231         return -EOPNOTSUPP;
232 }
233
234 /*
235  * The rip of IBS samples has skid 0. Thus, IBS supports precise
236  * levels 1 and 2 and the PERF_EFLAGS_EXACT is set. In rare cases the
237  * rip is invalid when IBS was not able to record the rip correctly.
238  * We clear PERF_EFLAGS_EXACT and take the rip from pt_regs then.
239  */
240 int forward_event_to_ibs(struct perf_event *event)
241 {
242         u64 config = 0;
243
244         if (!event->attr.precise_ip || event->attr.precise_ip > 2)
245                 return -EOPNOTSUPP;
246
247         if (!core_pmu_ibs_config(event, &config)) {
248                 event->attr.type = perf_ibs_op.pmu.type;
249                 event->attr.config = config;
250         }
251         return -ENOENT;
252 }
253
254 static int perf_ibs_init(struct perf_event *event)
255 {
256         struct hw_perf_event *hwc = &event->hw;
257         struct perf_ibs *perf_ibs;
258         u64 max_cnt, config;
259
260         perf_ibs = get_ibs_pmu(event->attr.type);
261         if (!perf_ibs)
262                 return -ENOENT;
263
264         config = event->attr.config;
265
266         if (event->pmu != &perf_ibs->pmu)
267                 return -ENOENT;
268
269         if (config & ~perf_ibs->config_mask)
270                 return -EINVAL;
271
272         if (hwc->sample_period) {
273                 if (config & perf_ibs->cnt_mask)
274                         /* raw max_cnt may not be set */
275                         return -EINVAL;
276                 if (!event->attr.sample_freq && hwc->sample_period & 0x0f)
277                         /*
278                          * lower 4 bits can not be set in ibs max cnt,
279                          * but allowing it in case we adjust the
280                          * sample period to set a frequency.
281                          */
282                         return -EINVAL;
283                 hwc->sample_period &= ~0x0FULL;
284                 if (!hwc->sample_period)
285                         hwc->sample_period = 0x10;
286         } else {
287                 max_cnt = config & perf_ibs->cnt_mask;
288                 config &= ~perf_ibs->cnt_mask;
289                 event->attr.sample_period = max_cnt << 4;
290                 hwc->sample_period = event->attr.sample_period;
291         }
292
293         if (!hwc->sample_period)
294                 return -EINVAL;
295
296         /*
297          * If we modify hwc->sample_period, we also need to update
298          * hwc->last_period and hwc->period_left.
299          */
300         hwc->last_period = hwc->sample_period;
301         local64_set(&hwc->period_left, hwc->sample_period);
302
303         hwc->config_base = perf_ibs->msr;
304         hwc->config = config;
305
306         /*
307          * rip recorded by IbsOpRip will not be consistent with rsp and rbp
308          * recorded as part of interrupt regs. Thus we need to use rip from
309          * interrupt regs while unwinding call stack. Setting _EARLY flag
310          * makes sure we unwind call-stack before perf sample rip is set to
311          * IbsOpRip.
312          */
313         if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
314                 event->attr.sample_type |= __PERF_SAMPLE_CALLCHAIN_EARLY;
315
316         return 0;
317 }
318
319 static int perf_ibs_set_period(struct perf_ibs *perf_ibs,
320                                struct hw_perf_event *hwc, u64 *period)
321 {
322         int overflow;
323
324         /* ignore lower 4 bits in min count: */
325         overflow = perf_event_set_period(hwc, 1<<4, perf_ibs->max_period, period);
326         local64_set(&hwc->prev_count, 0);
327
328         return overflow;
329 }
330
331 static u64 get_ibs_fetch_count(u64 config)
332 {
333         union ibs_fetch_ctl fetch_ctl = (union ibs_fetch_ctl)config;
334
335         return fetch_ctl.fetch_cnt << 4;
336 }
337
338 static u64 get_ibs_op_count(u64 config)
339 {
340         union ibs_op_ctl op_ctl = (union ibs_op_ctl)config;
341         u64 count = 0;
342
343         /*
344          * If the internal 27-bit counter rolled over, the count is MaxCnt
345          * and the lower 7 bits of CurCnt are randomized.
346          * Otherwise CurCnt has the full 27-bit current counter value.
347          */
348         if (op_ctl.op_val) {
349                 count = op_ctl.opmaxcnt << 4;
350                 if (ibs_caps & IBS_CAPS_OPCNTEXT)
351                         count += op_ctl.opmaxcnt_ext << 20;
352         } else if (ibs_caps & IBS_CAPS_RDWROPCNT) {
353                 count = op_ctl.opcurcnt;
354         }
355
356         return count;
357 }
358
359 static void
360 perf_ibs_event_update(struct perf_ibs *perf_ibs, struct perf_event *event,
361                       u64 *config)
362 {
363         u64 count = perf_ibs->get_count(*config);
364
365         /*
366          * Set width to 64 since we do not overflow on max width but
367          * instead on max count. In perf_ibs_set_period() we clear
368          * prev count manually on overflow.
369          */
370         while (!perf_event_try_update(event, count, 64)) {
371                 rdmsrl(event->hw.config_base, *config);
372                 count = perf_ibs->get_count(*config);
373         }
374 }
375
376 static inline void perf_ibs_enable_event(struct perf_ibs *perf_ibs,
377                                          struct hw_perf_event *hwc, u64 config)
378 {
379         u64 tmp = hwc->config | config;
380
381         if (perf_ibs->fetch_count_reset_broken)
382                 wrmsrl(hwc->config_base, tmp & ~perf_ibs->enable_mask);
383
384         wrmsrl(hwc->config_base, tmp | perf_ibs->enable_mask);
385 }
386
387 /*
388  * Erratum #420 Instruction-Based Sampling Engine May Generate
389  * Interrupt that Cannot Be Cleared:
390  *
391  * Must clear counter mask first, then clear the enable bit. See
392  * Revision Guide for AMD Family 10h Processors, Publication #41322.
393  */
394 static inline void perf_ibs_disable_event(struct perf_ibs *perf_ibs,
395                                           struct hw_perf_event *hwc, u64 config)
396 {
397         config &= ~perf_ibs->cnt_mask;
398         if (boot_cpu_data.x86 == 0x10)
399                 wrmsrl(hwc->config_base, config);
400         config &= ~perf_ibs->enable_mask;
401         wrmsrl(hwc->config_base, config);
402 }
403
404 /*
405  * We cannot restore the ibs pmu state, so we always needs to update
406  * the event while stopping it and then reset the state when starting
407  * again. Thus, ignoring PERF_EF_RELOAD and PERF_EF_UPDATE flags in
408  * perf_ibs_start()/perf_ibs_stop() and instead always do it.
409  */
410 static void perf_ibs_start(struct perf_event *event, int flags)
411 {
412         struct hw_perf_event *hwc = &event->hw;
413         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
414         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
415         u64 period, config = 0;
416
417         if (WARN_ON_ONCE(!(hwc->state & PERF_HES_STOPPED)))
418                 return;
419
420         WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE));
421         hwc->state = 0;
422
423         perf_ibs_set_period(perf_ibs, hwc, &period);
424         if (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_OPCNTEXT)) {
425                 config |= period & IBS_OP_MAX_CNT_EXT_MASK;
426                 period &= ~IBS_OP_MAX_CNT_EXT_MASK;
427         }
428         config |= period >> 4;
429
430         /*
431          * Set STARTED before enabling the hardware, such that a subsequent NMI
432          * must observe it.
433          */
434         set_bit(IBS_STARTED,    pcpu->state);
435         clear_bit(IBS_STOPPING, pcpu->state);
436         perf_ibs_enable_event(perf_ibs, hwc, config);
437
438         perf_event_update_userpage(event);
439 }
440
441 static void perf_ibs_stop(struct perf_event *event, int flags)
442 {
443         struct hw_perf_event *hwc = &event->hw;
444         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
445         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
446         u64 config;
447         int stopping;
448
449         if (test_and_set_bit(IBS_STOPPING, pcpu->state))
450                 return;
451
452         stopping = test_bit(IBS_STARTED, pcpu->state);
453
454         if (!stopping && (hwc->state & PERF_HES_UPTODATE))
455                 return;
456
457         rdmsrl(hwc->config_base, config);
458
459         if (stopping) {
460                 /*
461                  * Set STOPPED before disabling the hardware, such that it
462                  * must be visible to NMIs the moment we clear the EN bit,
463                  * at which point we can generate an !VALID sample which
464                  * we need to consume.
465                  */
466                 set_bit(IBS_STOPPED, pcpu->state);
467                 perf_ibs_disable_event(perf_ibs, hwc, config);
468                 /*
469                  * Clear STARTED after disabling the hardware; if it were
470                  * cleared before an NMI hitting after the clear but before
471                  * clearing the EN bit might think it a spurious NMI and not
472                  * handle it.
473                  *
474                  * Clearing it after, however, creates the problem of the NMI
475                  * handler seeing STARTED but not having a valid sample.
476                  */
477                 clear_bit(IBS_STARTED, pcpu->state);
478                 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
479                 hwc->state |= PERF_HES_STOPPED;
480         }
481
482         if (hwc->state & PERF_HES_UPTODATE)
483                 return;
484
485         /*
486          * Clear valid bit to not count rollovers on update, rollovers
487          * are only updated in the irq handler.
488          */
489         config &= ~perf_ibs->valid_mask;
490
491         perf_ibs_event_update(perf_ibs, event, &config);
492         hwc->state |= PERF_HES_UPTODATE;
493 }
494
495 static int perf_ibs_add(struct perf_event *event, int flags)
496 {
497         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
498         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
499
500         if (test_and_set_bit(IBS_ENABLED, pcpu->state))
501                 return -ENOSPC;
502
503         event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
504
505         pcpu->event = event;
506
507         if (flags & PERF_EF_START)
508                 perf_ibs_start(event, PERF_EF_RELOAD);
509
510         return 0;
511 }
512
513 static void perf_ibs_del(struct perf_event *event, int flags)
514 {
515         struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
516         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
517
518         if (!test_and_clear_bit(IBS_ENABLED, pcpu->state))
519                 return;
520
521         perf_ibs_stop(event, PERF_EF_UPDATE);
522
523         pcpu->event = NULL;
524
525         perf_event_update_userpage(event);
526 }
527
528 static void perf_ibs_read(struct perf_event *event) { }
529
530 PMU_FORMAT_ATTR(rand_en,        "config:57");
531 PMU_FORMAT_ATTR(cnt_ctl,        "config:19");
532
533 static struct attribute *ibs_fetch_format_attrs[] = {
534         &format_attr_rand_en.attr,
535         NULL,
536 };
537
538 static struct attribute *ibs_op_format_attrs[] = {
539         NULL,   /* &format_attr_cnt_ctl.attr if IBS_CAPS_OPCNT */
540         NULL,
541 };
542
543 static struct perf_ibs perf_ibs_fetch = {
544         .pmu = {
545                 .task_ctx_nr    = perf_invalid_context,
546
547                 .event_init     = perf_ibs_init,
548                 .add            = perf_ibs_add,
549                 .del            = perf_ibs_del,
550                 .start          = perf_ibs_start,
551                 .stop           = perf_ibs_stop,
552                 .read           = perf_ibs_read,
553                 .capabilities   = PERF_PMU_CAP_NO_EXCLUDE,
554         },
555         .msr                    = MSR_AMD64_IBSFETCHCTL,
556         .config_mask            = IBS_FETCH_CONFIG_MASK,
557         .cnt_mask               = IBS_FETCH_MAX_CNT,
558         .enable_mask            = IBS_FETCH_ENABLE,
559         .valid_mask             = IBS_FETCH_VAL,
560         .max_period             = IBS_FETCH_MAX_CNT << 4,
561         .offset_mask            = { MSR_AMD64_IBSFETCH_REG_MASK },
562         .offset_max             = MSR_AMD64_IBSFETCH_REG_COUNT,
563         .format_attrs           = ibs_fetch_format_attrs,
564
565         .get_count              = get_ibs_fetch_count,
566 };
567
568 static struct perf_ibs perf_ibs_op = {
569         .pmu = {
570                 .task_ctx_nr    = perf_invalid_context,
571
572                 .event_init     = perf_ibs_init,
573                 .add            = perf_ibs_add,
574                 .del            = perf_ibs_del,
575                 .start          = perf_ibs_start,
576                 .stop           = perf_ibs_stop,
577                 .read           = perf_ibs_read,
578                 .capabilities   = PERF_PMU_CAP_NO_EXCLUDE,
579         },
580         .msr                    = MSR_AMD64_IBSOPCTL,
581         .config_mask            = IBS_OP_CONFIG_MASK,
582         .cnt_mask               = IBS_OP_MAX_CNT | IBS_OP_CUR_CNT |
583                                   IBS_OP_CUR_CNT_RAND,
584         .enable_mask            = IBS_OP_ENABLE,
585         .valid_mask             = IBS_OP_VAL,
586         .max_period             = IBS_OP_MAX_CNT << 4,
587         .offset_mask            = { MSR_AMD64_IBSOP_REG_MASK },
588         .offset_max             = MSR_AMD64_IBSOP_REG_COUNT,
589         .format_attrs           = ibs_op_format_attrs,
590
591         .get_count              = get_ibs_op_count,
592 };
593
594 static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs)
595 {
596         struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
597         struct perf_event *event = pcpu->event;
598         struct hw_perf_event *hwc;
599         struct perf_sample_data data;
600         struct perf_raw_record raw;
601         struct pt_regs regs;
602         struct perf_ibs_data ibs_data;
603         int offset, size, check_rip, offset_max, throttle = 0;
604         unsigned int msr;
605         u64 *buf, *config, period, new_config = 0;
606
607         if (!test_bit(IBS_STARTED, pcpu->state)) {
608 fail:
609                 /*
610                  * Catch spurious interrupts after stopping IBS: After
611                  * disabling IBS there could be still incoming NMIs
612                  * with samples that even have the valid bit cleared.
613                  * Mark all this NMIs as handled.
614                  */
615                 if (test_and_clear_bit(IBS_STOPPED, pcpu->state))
616                         return 1;
617
618                 return 0;
619         }
620
621         if (WARN_ON_ONCE(!event))
622                 goto fail;
623
624         hwc = &event->hw;
625         msr = hwc->config_base;
626         buf = ibs_data.regs;
627         rdmsrl(msr, *buf);
628         if (!(*buf++ & perf_ibs->valid_mask))
629                 goto fail;
630
631         config = &ibs_data.regs[0];
632         perf_ibs_event_update(perf_ibs, event, config);
633         perf_sample_data_init(&data, 0, hwc->last_period);
634         if (!perf_ibs_set_period(perf_ibs, hwc, &period))
635                 goto out;       /* no sw counter overflow */
636
637         ibs_data.caps = ibs_caps;
638         size = 1;
639         offset = 1;
640         check_rip = (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_RIPINVALIDCHK));
641         if (event->attr.sample_type & PERF_SAMPLE_RAW)
642                 offset_max = perf_ibs->offset_max;
643         else if (check_rip)
644                 offset_max = 3;
645         else
646                 offset_max = 1;
647         do {
648                 rdmsrl(msr + offset, *buf++);
649                 size++;
650                 offset = find_next_bit(perf_ibs->offset_mask,
651                                        perf_ibs->offset_max,
652                                        offset + 1);
653         } while (offset < offset_max);
654         /*
655          * Read IbsBrTarget, IbsOpData4, and IbsExtdCtl separately
656          * depending on their availability.
657          * Can't add to offset_max as they are staggered
658          */
659         if (event->attr.sample_type & PERF_SAMPLE_RAW) {
660                 if (perf_ibs == &perf_ibs_op) {
661                         if (ibs_caps & IBS_CAPS_BRNTRGT) {
662                                 rdmsrl(MSR_AMD64_IBSBRTARGET, *buf++);
663                                 size++;
664                         }
665                         if (ibs_caps & IBS_CAPS_OPDATA4) {
666                                 rdmsrl(MSR_AMD64_IBSOPDATA4, *buf++);
667                                 size++;
668                         }
669                 }
670                 if (perf_ibs == &perf_ibs_fetch && (ibs_caps & IBS_CAPS_FETCHCTLEXTD)) {
671                         rdmsrl(MSR_AMD64_ICIBSEXTDCTL, *buf++);
672                         size++;
673                 }
674         }
675         ibs_data.size = sizeof(u64) * size;
676
677         regs = *iregs;
678         if (check_rip && (ibs_data.regs[2] & IBS_RIP_INVALID)) {
679                 regs.flags &= ~PERF_EFLAGS_EXACT;
680         } else {
681                 /* Workaround for erratum #1197 */
682                 if (perf_ibs->fetch_ignore_if_zero_rip && !(ibs_data.regs[1]))
683                         goto out;
684
685                 set_linear_ip(&regs, ibs_data.regs[1]);
686                 regs.flags |= PERF_EFLAGS_EXACT;
687         }
688
689         if (event->attr.sample_type & PERF_SAMPLE_RAW) {
690                 raw = (struct perf_raw_record){
691                         .frag = {
692                                 .size = sizeof(u32) + ibs_data.size,
693                                 .data = ibs_data.data,
694                         },
695                 };
696                 data.raw = &raw;
697         }
698
699         /*
700          * rip recorded by IbsOpRip will not be consistent with rsp and rbp
701          * recorded as part of interrupt regs. Thus we need to use rip from
702          * interrupt regs while unwinding call stack.
703          */
704         if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
705                 data.callchain = perf_callchain(event, iregs);
706
707         throttle = perf_event_overflow(event, &data, &regs);
708 out:
709         if (throttle) {
710                 perf_ibs_stop(event, 0);
711         } else {
712                 if (perf_ibs == &perf_ibs_op) {
713                         if (ibs_caps & IBS_CAPS_OPCNTEXT) {
714                                 new_config = period & IBS_OP_MAX_CNT_EXT_MASK;
715                                 period &= ~IBS_OP_MAX_CNT_EXT_MASK;
716                         }
717                         if ((ibs_caps & IBS_CAPS_RDWROPCNT) && (*config & IBS_OP_CNT_CTL))
718                                 new_config |= *config & IBS_OP_CUR_CNT_RAND;
719                 }
720                 new_config |= period >> 4;
721
722                 perf_ibs_enable_event(perf_ibs, hwc, new_config);
723         }
724
725         perf_event_update_userpage(event);
726
727         return 1;
728 }
729
730 static int
731 perf_ibs_nmi_handler(unsigned int cmd, struct pt_regs *regs)
732 {
733         u64 stamp = sched_clock();
734         int handled = 0;
735
736         handled += perf_ibs_handle_irq(&perf_ibs_fetch, regs);
737         handled += perf_ibs_handle_irq(&perf_ibs_op, regs);
738
739         if (handled)
740                 inc_irq_stat(apic_perf_irqs);
741
742         perf_sample_event_took(sched_clock() - stamp);
743
744         return handled;
745 }
746 NOKPROBE_SYMBOL(perf_ibs_nmi_handler);
747
748 static __init int perf_ibs_pmu_init(struct perf_ibs *perf_ibs, char *name)
749 {
750         struct cpu_perf_ibs __percpu *pcpu;
751         int ret;
752
753         pcpu = alloc_percpu(struct cpu_perf_ibs);
754         if (!pcpu)
755                 return -ENOMEM;
756
757         perf_ibs->pcpu = pcpu;
758
759         /* register attributes */
760         if (perf_ibs->format_attrs[0]) {
761                 memset(&perf_ibs->format_group, 0, sizeof(perf_ibs->format_group));
762                 perf_ibs->format_group.name     = "format";
763                 perf_ibs->format_group.attrs    = perf_ibs->format_attrs;
764
765                 memset(&perf_ibs->attr_groups, 0, sizeof(perf_ibs->attr_groups));
766                 perf_ibs->attr_groups[0]        = &perf_ibs->format_group;
767                 perf_ibs->pmu.attr_groups       = perf_ibs->attr_groups;
768         }
769
770         ret = perf_pmu_register(&perf_ibs->pmu, name, -1);
771         if (ret) {
772                 perf_ibs->pcpu = NULL;
773                 free_percpu(pcpu);
774         }
775
776         return ret;
777 }
778
779 static __init int perf_event_ibs_init(void)
780 {
781         struct attribute **attr = ibs_op_format_attrs;
782         int ret;
783
784         /*
785          * Some chips fail to reset the fetch count when it is written; instead
786          * they need a 0-1 transition of IbsFetchEn.
787          */
788         if (boot_cpu_data.x86 >= 0x16 && boot_cpu_data.x86 <= 0x18)
789                 perf_ibs_fetch.fetch_count_reset_broken = 1;
790
791         if (boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model < 0x10)
792                 perf_ibs_fetch.fetch_ignore_if_zero_rip = 1;
793
794         ret = perf_ibs_pmu_init(&perf_ibs_fetch, "ibs_fetch");
795         if (ret)
796                 return ret;
797
798         if (ibs_caps & IBS_CAPS_OPCNT) {
799                 perf_ibs_op.config_mask |= IBS_OP_CNT_CTL;
800                 *attr++ = &format_attr_cnt_ctl.attr;
801         }
802
803         if (ibs_caps & IBS_CAPS_OPCNTEXT) {
804                 perf_ibs_op.max_period  |= IBS_OP_MAX_CNT_EXT_MASK;
805                 perf_ibs_op.config_mask |= IBS_OP_MAX_CNT_EXT_MASK;
806                 perf_ibs_op.cnt_mask    |= IBS_OP_MAX_CNT_EXT_MASK;
807         }
808
809         ret = perf_ibs_pmu_init(&perf_ibs_op, "ibs_op");
810         if (ret)
811                 goto err_op;
812
813         ret = register_nmi_handler(NMI_LOCAL, perf_ibs_nmi_handler, 0, "perf_ibs");
814         if (ret)
815                 goto err_nmi;
816
817         pr_info("perf: AMD IBS detected (0x%08x)\n", ibs_caps);
818         return 0;
819
820 err_nmi:
821         perf_pmu_unregister(&perf_ibs_op.pmu);
822         free_percpu(perf_ibs_op.pcpu);
823         perf_ibs_op.pcpu = NULL;
824 err_op:
825         perf_pmu_unregister(&perf_ibs_fetch.pmu);
826         free_percpu(perf_ibs_fetch.pcpu);
827         perf_ibs_fetch.pcpu = NULL;
828
829         return ret;
830 }
831
832 #else /* defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_AMD) */
833
834 static __init int perf_event_ibs_init(void)
835 {
836         return 0;
837 }
838
839 #endif
840
841 /* IBS - apic initialization, for perf and oprofile */
842
843 static __init u32 __get_ibs_caps(void)
844 {
845         u32 caps;
846         unsigned int max_level;
847
848         if (!boot_cpu_has(X86_FEATURE_IBS))
849                 return 0;
850
851         /* check IBS cpuid feature flags */
852         max_level = cpuid_eax(0x80000000);
853         if (max_level < IBS_CPUID_FEATURES)
854                 return IBS_CAPS_DEFAULT;
855
856         caps = cpuid_eax(IBS_CPUID_FEATURES);
857         if (!(caps & IBS_CAPS_AVAIL))
858                 /* cpuid flags not valid */
859                 return IBS_CAPS_DEFAULT;
860
861         return caps;
862 }
863
864 u32 get_ibs_caps(void)
865 {
866         return ibs_caps;
867 }
868
869 EXPORT_SYMBOL(get_ibs_caps);
870
871 static inline int get_eilvt(int offset)
872 {
873         return !setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 1);
874 }
875
876 static inline int put_eilvt(int offset)
877 {
878         return !setup_APIC_eilvt(offset, 0, 0, 1);
879 }
880
881 /*
882  * Check and reserve APIC extended interrupt LVT offset for IBS if available.
883  */
884 static inline int ibs_eilvt_valid(void)
885 {
886         int offset;
887         u64 val;
888         int valid = 0;
889
890         preempt_disable();
891
892         rdmsrl(MSR_AMD64_IBSCTL, val);
893         offset = val & IBSCTL_LVT_OFFSET_MASK;
894
895         if (!(val & IBSCTL_LVT_OFFSET_VALID)) {
896                 pr_err(FW_BUG "cpu %d, invalid IBS interrupt offset %d (MSR%08X=0x%016llx)\n",
897                        smp_processor_id(), offset, MSR_AMD64_IBSCTL, val);
898                 goto out;
899         }
900
901         if (!get_eilvt(offset)) {
902                 pr_err(FW_BUG "cpu %d, IBS interrupt offset %d not available (MSR%08X=0x%016llx)\n",
903                        smp_processor_id(), offset, MSR_AMD64_IBSCTL, val);
904                 goto out;
905         }
906
907         valid = 1;
908 out:
909         preempt_enable();
910
911         return valid;
912 }
913
914 static int setup_ibs_ctl(int ibs_eilvt_off)
915 {
916         struct pci_dev *cpu_cfg;
917         int nodes;
918         u32 value = 0;
919
920         nodes = 0;
921         cpu_cfg = NULL;
922         do {
923                 cpu_cfg = pci_get_device(PCI_VENDOR_ID_AMD,
924                                          PCI_DEVICE_ID_AMD_10H_NB_MISC,
925                                          cpu_cfg);
926                 if (!cpu_cfg)
927                         break;
928                 ++nodes;
929                 pci_write_config_dword(cpu_cfg, IBSCTL, ibs_eilvt_off
930                                        | IBSCTL_LVT_OFFSET_VALID);
931                 pci_read_config_dword(cpu_cfg, IBSCTL, &value);
932                 if (value != (ibs_eilvt_off | IBSCTL_LVT_OFFSET_VALID)) {
933                         pci_dev_put(cpu_cfg);
934                         pr_debug("Failed to setup IBS LVT offset, IBSCTL = 0x%08x\n",
935                                  value);
936                         return -EINVAL;
937                 }
938         } while (1);
939
940         if (!nodes) {
941                 pr_debug("No CPU node configured for IBS\n");
942                 return -ENODEV;
943         }
944
945         return 0;
946 }
947
948 /*
949  * This runs only on the current cpu. We try to find an LVT offset and
950  * setup the local APIC. For this we must disable preemption. On
951  * success we initialize all nodes with this offset. This updates then
952  * the offset in the IBS_CTL per-node msr. The per-core APIC setup of
953  * the IBS interrupt vector is handled by perf_ibs_cpu_notifier that
954  * is using the new offset.
955  */
956 static void force_ibs_eilvt_setup(void)
957 {
958         int offset;
959         int ret;
960
961         preempt_disable();
962         /* find the next free available EILVT entry, skip offset 0 */
963         for (offset = 1; offset < APIC_EILVT_NR_MAX; offset++) {
964                 if (get_eilvt(offset))
965                         break;
966         }
967         preempt_enable();
968
969         if (offset == APIC_EILVT_NR_MAX) {
970                 pr_debug("No EILVT entry available\n");
971                 return;
972         }
973
974         ret = setup_ibs_ctl(offset);
975         if (ret)
976                 goto out;
977
978         if (!ibs_eilvt_valid())
979                 goto out;
980
981         pr_info("LVT offset %d assigned\n", offset);
982
983         return;
984 out:
985         preempt_disable();
986         put_eilvt(offset);
987         preempt_enable();
988         return;
989 }
990
991 static void ibs_eilvt_setup(void)
992 {
993         /*
994          * Force LVT offset assignment for family 10h: The offsets are
995          * not assigned by the BIOS for this family, so the OS is
996          * responsible for doing it. If the OS assignment fails, fall
997          * back to BIOS settings and try to setup this.
998          */
999         if (boot_cpu_data.x86 == 0x10)
1000                 force_ibs_eilvt_setup();
1001 }
1002
1003 static inline int get_ibs_lvt_offset(void)
1004 {
1005         u64 val;
1006
1007         rdmsrl(MSR_AMD64_IBSCTL, val);
1008         if (!(val & IBSCTL_LVT_OFFSET_VALID))
1009                 return -EINVAL;
1010
1011         return val & IBSCTL_LVT_OFFSET_MASK;
1012 }
1013
1014 static void setup_APIC_ibs(void)
1015 {
1016         int offset;
1017
1018         offset = get_ibs_lvt_offset();
1019         if (offset < 0)
1020                 goto failed;
1021
1022         if (!setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 0))
1023                 return;
1024 failed:
1025         pr_warn("perf: IBS APIC setup failed on cpu #%d\n",
1026                 smp_processor_id());
1027 }
1028
1029 static void clear_APIC_ibs(void)
1030 {
1031         int offset;
1032
1033         offset = get_ibs_lvt_offset();
1034         if (offset >= 0)
1035                 setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_FIX, 1);
1036 }
1037
1038 static int x86_pmu_amd_ibs_starting_cpu(unsigned int cpu)
1039 {
1040         setup_APIC_ibs();
1041         return 0;
1042 }
1043
1044 #ifdef CONFIG_PM
1045
1046 static int perf_ibs_suspend(void)
1047 {
1048         clear_APIC_ibs();
1049         return 0;
1050 }
1051
1052 static void perf_ibs_resume(void)
1053 {
1054         ibs_eilvt_setup();
1055         setup_APIC_ibs();
1056 }
1057
1058 static struct syscore_ops perf_ibs_syscore_ops = {
1059         .resume         = perf_ibs_resume,
1060         .suspend        = perf_ibs_suspend,
1061 };
1062
1063 static void perf_ibs_pm_init(void)
1064 {
1065         register_syscore_ops(&perf_ibs_syscore_ops);
1066 }
1067
1068 #else
1069
1070 static inline void perf_ibs_pm_init(void) { }
1071
1072 #endif
1073
1074 static int x86_pmu_amd_ibs_dying_cpu(unsigned int cpu)
1075 {
1076         clear_APIC_ibs();
1077         return 0;
1078 }
1079
1080 static __init int amd_ibs_init(void)
1081 {
1082         u32 caps;
1083
1084         caps = __get_ibs_caps();
1085         if (!caps)
1086                 return -ENODEV; /* ibs not supported by the cpu */
1087
1088         ibs_eilvt_setup();
1089
1090         if (!ibs_eilvt_valid())
1091                 return -EINVAL;
1092
1093         perf_ibs_pm_init();
1094
1095         ibs_caps = caps;
1096         /* make ibs_caps visible to other cpus: */
1097         smp_mb();
1098         /*
1099          * x86_pmu_amd_ibs_starting_cpu will be called from core on
1100          * all online cpus.
1101          */
1102         cpuhp_setup_state(CPUHP_AP_PERF_X86_AMD_IBS_STARTING,
1103                           "perf/x86/amd/ibs:starting",
1104                           x86_pmu_amd_ibs_starting_cpu,
1105                           x86_pmu_amd_ibs_dying_cpu);
1106
1107         return perf_event_ibs_init();
1108 }
1109
1110 /* Since we need the pci subsystem to init ibs we can't do this earlier: */
1111 device_initcall(amd_ibs_init);