Linux-libre 4.9.189-gnu
[librecmc/linux-libre.git] / drivers / perf / arm_pmu.c
1 #undef DEBUG
2
3 /*
4  * ARM performance counter support.
5  *
6  * Copyright (C) 2009 picoChip Designs, Ltd., Jamie Iles
7  * Copyright (C) 2010 ARM Ltd., Will Deacon <will.deacon@arm.com>
8  *
9  * This code is based on the sparc64 perf event code, which is in turn based
10  * on the x86 code.
11  */
12 #define pr_fmt(fmt) "hw perfevents: " fmt
13
14 #include <linux/bitmap.h>
15 #include <linux/cpumask.h>
16 #include <linux/cpu_pm.h>
17 #include <linux/export.h>
18 #include <linux/kernel.h>
19 #include <linux/of_device.h>
20 #include <linux/perf/arm_pmu.h>
21 #include <linux/platform_device.h>
22 #include <linux/slab.h>
23 #include <linux/spinlock.h>
24 #include <linux/irq.h>
25 #include <linux/irqdesc.h>
26
27 #include <asm/cputype.h>
28 #include <asm/irq_regs.h>
29
30 static int
31 armpmu_map_cache_event(const unsigned (*cache_map)
32                                       [PERF_COUNT_HW_CACHE_MAX]
33                                       [PERF_COUNT_HW_CACHE_OP_MAX]
34                                       [PERF_COUNT_HW_CACHE_RESULT_MAX],
35                        u64 config)
36 {
37         unsigned int cache_type, cache_op, cache_result, ret;
38
39         cache_type = (config >>  0) & 0xff;
40         if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
41                 return -EINVAL;
42
43         cache_op = (config >>  8) & 0xff;
44         if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
45                 return -EINVAL;
46
47         cache_result = (config >> 16) & 0xff;
48         if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
49                 return -EINVAL;
50
51         ret = (int)(*cache_map)[cache_type][cache_op][cache_result];
52
53         if (ret == CACHE_OP_UNSUPPORTED)
54                 return -ENOENT;
55
56         return ret;
57 }
58
59 static int
60 armpmu_map_hw_event(const unsigned (*event_map)[PERF_COUNT_HW_MAX], u64 config)
61 {
62         int mapping;
63
64         if (config >= PERF_COUNT_HW_MAX)
65                 return -EINVAL;
66
67         mapping = (*event_map)[config];
68         return mapping == HW_OP_UNSUPPORTED ? -ENOENT : mapping;
69 }
70
71 static int
72 armpmu_map_raw_event(u32 raw_event_mask, u64 config)
73 {
74         return (int)(config & raw_event_mask);
75 }
76
77 int
78 armpmu_map_event(struct perf_event *event,
79                  const unsigned (*event_map)[PERF_COUNT_HW_MAX],
80                  const unsigned (*cache_map)
81                                 [PERF_COUNT_HW_CACHE_MAX]
82                                 [PERF_COUNT_HW_CACHE_OP_MAX]
83                                 [PERF_COUNT_HW_CACHE_RESULT_MAX],
84                  u32 raw_event_mask)
85 {
86         u64 config = event->attr.config;
87         int type = event->attr.type;
88
89         if (type == event->pmu->type)
90                 return armpmu_map_raw_event(raw_event_mask, config);
91
92         switch (type) {
93         case PERF_TYPE_HARDWARE:
94                 return armpmu_map_hw_event(event_map, config);
95         case PERF_TYPE_HW_CACHE:
96                 return armpmu_map_cache_event(cache_map, config);
97         case PERF_TYPE_RAW:
98                 return armpmu_map_raw_event(raw_event_mask, config);
99         }
100
101         return -ENOENT;
102 }
103
104 int armpmu_event_set_period(struct perf_event *event)
105 {
106         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
107         struct hw_perf_event *hwc = &event->hw;
108         s64 left = local64_read(&hwc->period_left);
109         s64 period = hwc->sample_period;
110         int ret = 0;
111
112         if (unlikely(left <= -period)) {
113                 left = period;
114                 local64_set(&hwc->period_left, left);
115                 hwc->last_period = period;
116                 ret = 1;
117         }
118
119         if (unlikely(left <= 0)) {
120                 left += period;
121                 local64_set(&hwc->period_left, left);
122                 hwc->last_period = period;
123                 ret = 1;
124         }
125
126         /*
127          * Limit the maximum period to prevent the counter value
128          * from overtaking the one we are about to program. In
129          * effect we are reducing max_period to account for
130          * interrupt latency (and we are being very conservative).
131          */
132         if (left > (armpmu->max_period >> 1))
133                 left = armpmu->max_period >> 1;
134
135         local64_set(&hwc->prev_count, (u64)-left);
136
137         armpmu->write_counter(event, (u64)(-left) & 0xffffffff);
138
139         perf_event_update_userpage(event);
140
141         return ret;
142 }
143
144 u64 armpmu_event_update(struct perf_event *event)
145 {
146         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
147         struct hw_perf_event *hwc = &event->hw;
148         u64 delta, prev_raw_count, new_raw_count;
149
150 again:
151         prev_raw_count = local64_read(&hwc->prev_count);
152         new_raw_count = armpmu->read_counter(event);
153
154         if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
155                              new_raw_count) != prev_raw_count)
156                 goto again;
157
158         delta = (new_raw_count - prev_raw_count) & armpmu->max_period;
159
160         local64_add(delta, &event->count);
161         local64_sub(delta, &hwc->period_left);
162
163         return new_raw_count;
164 }
165
166 static void
167 armpmu_read(struct perf_event *event)
168 {
169         armpmu_event_update(event);
170 }
171
172 static void
173 armpmu_stop(struct perf_event *event, int flags)
174 {
175         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
176         struct hw_perf_event *hwc = &event->hw;
177
178         /*
179          * ARM pmu always has to update the counter, so ignore
180          * PERF_EF_UPDATE, see comments in armpmu_start().
181          */
182         if (!(hwc->state & PERF_HES_STOPPED)) {
183                 armpmu->disable(event);
184                 armpmu_event_update(event);
185                 hwc->state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
186         }
187 }
188
189 static void armpmu_start(struct perf_event *event, int flags)
190 {
191         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
192         struct hw_perf_event *hwc = &event->hw;
193
194         /*
195          * ARM pmu always has to reprogram the period, so ignore
196          * PERF_EF_RELOAD, see the comment below.
197          */
198         if (flags & PERF_EF_RELOAD)
199                 WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE));
200
201         hwc->state = 0;
202         /*
203          * Set the period again. Some counters can't be stopped, so when we
204          * were stopped we simply disabled the IRQ source and the counter
205          * may have been left counting. If we don't do this step then we may
206          * get an interrupt too soon or *way* too late if the overflow has
207          * happened since disabling.
208          */
209         armpmu_event_set_period(event);
210         armpmu->enable(event);
211 }
212
213 static void
214 armpmu_del(struct perf_event *event, int flags)
215 {
216         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
217         struct pmu_hw_events *hw_events = this_cpu_ptr(armpmu->hw_events);
218         struct hw_perf_event *hwc = &event->hw;
219         int idx = hwc->idx;
220
221         armpmu_stop(event, PERF_EF_UPDATE);
222         hw_events->events[idx] = NULL;
223         clear_bit(idx, hw_events->used_mask);
224         if (armpmu->clear_event_idx)
225                 armpmu->clear_event_idx(hw_events, event);
226
227         perf_event_update_userpage(event);
228 }
229
230 static int
231 armpmu_add(struct perf_event *event, int flags)
232 {
233         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
234         struct pmu_hw_events *hw_events = this_cpu_ptr(armpmu->hw_events);
235         struct hw_perf_event *hwc = &event->hw;
236         int idx;
237         int err = 0;
238
239         /* An event following a process won't be stopped earlier */
240         if (!cpumask_test_cpu(smp_processor_id(), &armpmu->supported_cpus))
241                 return -ENOENT;
242
243         perf_pmu_disable(event->pmu);
244
245         /* If we don't have a space for the counter then finish early. */
246         idx = armpmu->get_event_idx(hw_events, event);
247         if (idx < 0) {
248                 err = idx;
249                 goto out;
250         }
251
252         /*
253          * If there is an event in the counter we are going to use then make
254          * sure it is disabled.
255          */
256         event->hw.idx = idx;
257         armpmu->disable(event);
258         hw_events->events[idx] = event;
259
260         hwc->state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
261         if (flags & PERF_EF_START)
262                 armpmu_start(event, PERF_EF_RELOAD);
263
264         /* Propagate our changes to the userspace mapping. */
265         perf_event_update_userpage(event);
266
267 out:
268         perf_pmu_enable(event->pmu);
269         return err;
270 }
271
272 static int
273 validate_event(struct pmu *pmu, struct pmu_hw_events *hw_events,
274                                struct perf_event *event)
275 {
276         struct arm_pmu *armpmu;
277
278         if (is_software_event(event))
279                 return 1;
280
281         /*
282          * Reject groups spanning multiple HW PMUs (e.g. CPU + CCI). The
283          * core perf code won't check that the pmu->ctx == leader->ctx
284          * until after pmu->event_init(event).
285          */
286         if (event->pmu != pmu)
287                 return 0;
288
289         if (event->state < PERF_EVENT_STATE_OFF)
290                 return 1;
291
292         if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
293                 return 1;
294
295         armpmu = to_arm_pmu(event->pmu);
296         return armpmu->get_event_idx(hw_events, event) >= 0;
297 }
298
299 static int
300 validate_group(struct perf_event *event)
301 {
302         struct perf_event *sibling, *leader = event->group_leader;
303         struct pmu_hw_events fake_pmu;
304
305         /*
306          * Initialise the fake PMU. We only need to populate the
307          * used_mask for the purposes of validation.
308          */
309         memset(&fake_pmu.used_mask, 0, sizeof(fake_pmu.used_mask));
310
311         if (!validate_event(event->pmu, &fake_pmu, leader))
312                 return -EINVAL;
313
314         list_for_each_entry(sibling, &leader->sibling_list, group_entry) {
315                 if (!validate_event(event->pmu, &fake_pmu, sibling))
316                         return -EINVAL;
317         }
318
319         if (!validate_event(event->pmu, &fake_pmu, event))
320                 return -EINVAL;
321
322         return 0;
323 }
324
325 static struct arm_pmu_platdata *armpmu_get_platdata(struct arm_pmu *armpmu)
326 {
327         struct platform_device *pdev = armpmu->plat_device;
328
329         return pdev ? dev_get_platdata(&pdev->dev) : NULL;
330 }
331
332 static irqreturn_t armpmu_dispatch_irq(int irq, void *dev)
333 {
334         struct arm_pmu *armpmu;
335         struct arm_pmu_platdata *plat;
336         int ret;
337         u64 start_clock, finish_clock;
338
339         /*
340          * we request the IRQ with a (possibly percpu) struct arm_pmu**, but
341          * the handlers expect a struct arm_pmu*. The percpu_irq framework will
342          * do any necessary shifting, we just need to perform the first
343          * dereference.
344          */
345         armpmu = *(void **)dev;
346
347         plat = armpmu_get_platdata(armpmu);
348
349         start_clock = sched_clock();
350         if (plat && plat->handle_irq)
351                 ret = plat->handle_irq(irq, armpmu, armpmu->handle_irq);
352         else
353                 ret = armpmu->handle_irq(irq, armpmu);
354         finish_clock = sched_clock();
355
356         perf_sample_event_took(finish_clock - start_clock);
357         return ret;
358 }
359
360 static void
361 armpmu_release_hardware(struct arm_pmu *armpmu)
362 {
363         armpmu->free_irq(armpmu);
364 }
365
366 static int
367 armpmu_reserve_hardware(struct arm_pmu *armpmu)
368 {
369         int err = armpmu->request_irq(armpmu, armpmu_dispatch_irq);
370         if (err) {
371                 armpmu_release_hardware(armpmu);
372                 return err;
373         }
374
375         return 0;
376 }
377
378 static void
379 hw_perf_event_destroy(struct perf_event *event)
380 {
381         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
382         atomic_t *active_events  = &armpmu->active_events;
383         struct mutex *pmu_reserve_mutex = &armpmu->reserve_mutex;
384
385         if (atomic_dec_and_mutex_lock(active_events, pmu_reserve_mutex)) {
386                 armpmu_release_hardware(armpmu);
387                 mutex_unlock(pmu_reserve_mutex);
388         }
389 }
390
391 static int
392 event_requires_mode_exclusion(struct perf_event_attr *attr)
393 {
394         return attr->exclude_idle || attr->exclude_user ||
395                attr->exclude_kernel || attr->exclude_hv;
396 }
397
398 static int
399 __hw_perf_event_init(struct perf_event *event)
400 {
401         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
402         struct hw_perf_event *hwc = &event->hw;
403         int mapping;
404
405         mapping = armpmu->map_event(event);
406
407         if (mapping < 0) {
408                 pr_debug("event %x:%llx not supported\n", event->attr.type,
409                          event->attr.config);
410                 return mapping;
411         }
412
413         /*
414          * We don't assign an index until we actually place the event onto
415          * hardware. Use -1 to signify that we haven't decided where to put it
416          * yet. For SMP systems, each core has it's own PMU so we can't do any
417          * clever allocation or constraints checking at this point.
418          */
419         hwc->idx                = -1;
420         hwc->config_base        = 0;
421         hwc->config             = 0;
422         hwc->event_base         = 0;
423
424         /*
425          * Check whether we need to exclude the counter from certain modes.
426          */
427         if ((!armpmu->set_event_filter ||
428              armpmu->set_event_filter(hwc, &event->attr)) &&
429              event_requires_mode_exclusion(&event->attr)) {
430                 pr_debug("ARM performance counters do not support "
431                          "mode exclusion\n");
432                 return -EOPNOTSUPP;
433         }
434
435         /*
436          * Store the event encoding into the config_base field.
437          */
438         hwc->config_base            |= (unsigned long)mapping;
439
440         if (!is_sampling_event(event)) {
441                 /*
442                  * For non-sampling runs, limit the sample_period to half
443                  * of the counter width. That way, the new counter value
444                  * is far less likely to overtake the previous one unless
445                  * you have some serious IRQ latency issues.
446                  */
447                 hwc->sample_period  = armpmu->max_period >> 1;
448                 hwc->last_period    = hwc->sample_period;
449                 local64_set(&hwc->period_left, hwc->sample_period);
450         }
451
452         if (event->group_leader != event) {
453                 if (validate_group(event) != 0)
454                         return -EINVAL;
455         }
456
457         return 0;
458 }
459
460 static int armpmu_event_init(struct perf_event *event)
461 {
462         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
463         int err = 0;
464         atomic_t *active_events = &armpmu->active_events;
465
466         /*
467          * Reject CPU-affine events for CPUs that are of a different class to
468          * that which this PMU handles. Process-following events (where
469          * event->cpu == -1) can be migrated between CPUs, and thus we have to
470          * reject them later (in armpmu_add) if they're scheduled on a
471          * different class of CPU.
472          */
473         if (event->cpu != -1 &&
474                 !cpumask_test_cpu(event->cpu, &armpmu->supported_cpus))
475                 return -ENOENT;
476
477         /* does not support taken branch sampling */
478         if (has_branch_stack(event))
479                 return -EOPNOTSUPP;
480
481         if (armpmu->map_event(event) == -ENOENT)
482                 return -ENOENT;
483
484         event->destroy = hw_perf_event_destroy;
485
486         if (!atomic_inc_not_zero(active_events)) {
487                 mutex_lock(&armpmu->reserve_mutex);
488                 if (atomic_read(active_events) == 0)
489                         err = armpmu_reserve_hardware(armpmu);
490
491                 if (!err)
492                         atomic_inc(active_events);
493                 mutex_unlock(&armpmu->reserve_mutex);
494         }
495
496         if (err)
497                 return err;
498
499         err = __hw_perf_event_init(event);
500         if (err)
501                 hw_perf_event_destroy(event);
502
503         return err;
504 }
505
506 static void armpmu_enable(struct pmu *pmu)
507 {
508         struct arm_pmu *armpmu = to_arm_pmu(pmu);
509         struct pmu_hw_events *hw_events = this_cpu_ptr(armpmu->hw_events);
510         int enabled = bitmap_weight(hw_events->used_mask, armpmu->num_events);
511
512         /* For task-bound events we may be called on other CPUs */
513         if (!cpumask_test_cpu(smp_processor_id(), &armpmu->supported_cpus))
514                 return;
515
516         if (enabled)
517                 armpmu->start(armpmu);
518 }
519
520 static void armpmu_disable(struct pmu *pmu)
521 {
522         struct arm_pmu *armpmu = to_arm_pmu(pmu);
523
524         /* For task-bound events we may be called on other CPUs */
525         if (!cpumask_test_cpu(smp_processor_id(), &armpmu->supported_cpus))
526                 return;
527
528         armpmu->stop(armpmu);
529 }
530
531 /*
532  * In heterogeneous systems, events are specific to a particular
533  * microarchitecture, and aren't suitable for another. Thus, only match CPUs of
534  * the same microarchitecture.
535  */
536 static int armpmu_filter_match(struct perf_event *event)
537 {
538         struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
539         unsigned int cpu = smp_processor_id();
540         return cpumask_test_cpu(cpu, &armpmu->supported_cpus);
541 }
542
543 static ssize_t armpmu_cpumask_show(struct device *dev,
544                                    struct device_attribute *attr, char *buf)
545 {
546         struct arm_pmu *armpmu = to_arm_pmu(dev_get_drvdata(dev));
547         return cpumap_print_to_pagebuf(true, buf, &armpmu->supported_cpus);
548 }
549
550 static DEVICE_ATTR(cpus, S_IRUGO, armpmu_cpumask_show, NULL);
551
552 static struct attribute *armpmu_common_attrs[] = {
553         &dev_attr_cpus.attr,
554         NULL,
555 };
556
557 static struct attribute_group armpmu_common_attr_group = {
558         .attrs = armpmu_common_attrs,
559 };
560
561 static void armpmu_init(struct arm_pmu *armpmu)
562 {
563         atomic_set(&armpmu->active_events, 0);
564         mutex_init(&armpmu->reserve_mutex);
565
566         armpmu->pmu = (struct pmu) {
567                 .pmu_enable     = armpmu_enable,
568                 .pmu_disable    = armpmu_disable,
569                 .event_init     = armpmu_event_init,
570                 .add            = armpmu_add,
571                 .del            = armpmu_del,
572                 .start          = armpmu_start,
573                 .stop           = armpmu_stop,
574                 .read           = armpmu_read,
575                 .filter_match   = armpmu_filter_match,
576                 .attr_groups    = armpmu->attr_groups,
577         };
578         armpmu->attr_groups[ARMPMU_ATTR_GROUP_COMMON] =
579                 &armpmu_common_attr_group;
580 }
581
582 /* Set at runtime when we know what CPU type we are. */
583 static struct arm_pmu *__oprofile_cpu_pmu;
584
585 /*
586  * Despite the names, these two functions are CPU-specific and are used
587  * by the OProfile/perf code.
588  */
589 const char *perf_pmu_name(void)
590 {
591         if (!__oprofile_cpu_pmu)
592                 return NULL;
593
594         return __oprofile_cpu_pmu->name;
595 }
596 EXPORT_SYMBOL_GPL(perf_pmu_name);
597
598 int perf_num_counters(void)
599 {
600         int max_events = 0;
601
602         if (__oprofile_cpu_pmu != NULL)
603                 max_events = __oprofile_cpu_pmu->num_events;
604
605         return max_events;
606 }
607 EXPORT_SYMBOL_GPL(perf_num_counters);
608
609 static void cpu_pmu_enable_percpu_irq(void *data)
610 {
611         int irq = *(int *)data;
612
613         enable_percpu_irq(irq, IRQ_TYPE_NONE);
614 }
615
616 static void cpu_pmu_disable_percpu_irq(void *data)
617 {
618         int irq = *(int *)data;
619
620         disable_percpu_irq(irq);
621 }
622
623 static void cpu_pmu_free_irq(struct arm_pmu *cpu_pmu)
624 {
625         int i, irq, irqs;
626         struct platform_device *pmu_device = cpu_pmu->plat_device;
627         struct pmu_hw_events __percpu *hw_events = cpu_pmu->hw_events;
628
629         irqs = min(pmu_device->num_resources, num_possible_cpus());
630
631         irq = platform_get_irq(pmu_device, 0);
632         if (irq > 0 && irq_is_percpu(irq)) {
633                 on_each_cpu_mask(&cpu_pmu->supported_cpus,
634                                  cpu_pmu_disable_percpu_irq, &irq, 1);
635                 free_percpu_irq(irq, &hw_events->percpu_pmu);
636         } else {
637                 for (i = 0; i < irqs; ++i) {
638                         int cpu = i;
639
640                         if (cpu_pmu->irq_affinity)
641                                 cpu = cpu_pmu->irq_affinity[i];
642
643                         if (!cpumask_test_and_clear_cpu(cpu, &cpu_pmu->active_irqs))
644                                 continue;
645                         irq = platform_get_irq(pmu_device, i);
646                         if (irq > 0)
647                                 free_irq(irq, per_cpu_ptr(&hw_events->percpu_pmu, cpu));
648                 }
649         }
650 }
651
652 static int cpu_pmu_request_irq(struct arm_pmu *cpu_pmu, irq_handler_t handler)
653 {
654         int i, err, irq, irqs;
655         struct platform_device *pmu_device = cpu_pmu->plat_device;
656         struct pmu_hw_events __percpu *hw_events = cpu_pmu->hw_events;
657
658         if (!pmu_device)
659                 return -ENODEV;
660
661         irqs = min(pmu_device->num_resources, num_possible_cpus());
662         if (irqs < 1) {
663                 pr_warn_once("perf/ARM: No irqs for PMU defined, sampling events not supported\n");
664                 return 0;
665         }
666
667         irq = platform_get_irq(pmu_device, 0);
668         if (irq > 0 && irq_is_percpu(irq)) {
669                 err = request_percpu_irq(irq, handler, "arm-pmu",
670                                          &hw_events->percpu_pmu);
671                 if (err) {
672                         pr_err("unable to request IRQ%d for ARM PMU counters\n",
673                                 irq);
674                         return err;
675                 }
676
677                 on_each_cpu_mask(&cpu_pmu->supported_cpus,
678                                  cpu_pmu_enable_percpu_irq, &irq, 1);
679         } else {
680                 for (i = 0; i < irqs; ++i) {
681                         int cpu = i;
682
683                         err = 0;
684                         irq = platform_get_irq(pmu_device, i);
685                         if (irq < 0)
686                                 continue;
687
688                         if (cpu_pmu->irq_affinity)
689                                 cpu = cpu_pmu->irq_affinity[i];
690
691                         /*
692                          * If we have a single PMU interrupt that we can't shift,
693                          * assume that we're running on a uniprocessor machine and
694                          * continue. Otherwise, continue without this interrupt.
695                          */
696                         if (irq_set_affinity(irq, cpumask_of(cpu)) && irqs > 1) {
697                                 pr_warn("unable to set irq affinity (irq=%d, cpu=%u)\n",
698                                         irq, cpu);
699                                 continue;
700                         }
701
702                         err = request_irq(irq, handler,
703                                           IRQF_NOBALANCING | IRQF_NO_THREAD, "arm-pmu",
704                                           per_cpu_ptr(&hw_events->percpu_pmu, cpu));
705                         if (err) {
706                                 pr_err("unable to request IRQ%d for ARM PMU counters\n",
707                                         irq);
708                                 return err;
709                         }
710
711                         cpumask_set_cpu(cpu, &cpu_pmu->active_irqs);
712                 }
713         }
714
715         return 0;
716 }
717
718 /*
719  * PMU hardware loses all context when a CPU goes offline.
720  * When a CPU is hotplugged back in, since some hardware registers are
721  * UNKNOWN at reset, the PMU must be explicitly reset to avoid reading
722  * junk values out of them.
723  */
724 static int arm_perf_starting_cpu(unsigned int cpu, struct hlist_node *node)
725 {
726         struct arm_pmu *pmu = hlist_entry_safe(node, struct arm_pmu, node);
727
728         if (!cpumask_test_cpu(cpu, &pmu->supported_cpus))
729                 return 0;
730         if (pmu->reset)
731                 pmu->reset(pmu);
732         return 0;
733 }
734
735 #ifdef CONFIG_CPU_PM
736 static void cpu_pm_pmu_setup(struct arm_pmu *armpmu, unsigned long cmd)
737 {
738         struct pmu_hw_events *hw_events = this_cpu_ptr(armpmu->hw_events);
739         struct perf_event *event;
740         int idx;
741
742         for (idx = 0; idx < armpmu->num_events; idx++) {
743                 /*
744                  * If the counter is not used skip it, there is no
745                  * need of stopping/restarting it.
746                  */
747                 if (!test_bit(idx, hw_events->used_mask))
748                         continue;
749
750                 event = hw_events->events[idx];
751
752                 switch (cmd) {
753                 case CPU_PM_ENTER:
754                         /*
755                          * Stop and update the counter
756                          */
757                         armpmu_stop(event, PERF_EF_UPDATE);
758                         break;
759                 case CPU_PM_EXIT:
760                 case CPU_PM_ENTER_FAILED:
761                          /*
762                           * Restore and enable the counter.
763                           * armpmu_start() indirectly calls
764                           *
765                           * perf_event_update_userpage()
766                           *
767                           * that requires RCU read locking to be functional,
768                           * wrap the call within RCU_NONIDLE to make the
769                           * RCU subsystem aware this cpu is not idle from
770                           * an RCU perspective for the armpmu_start() call
771                           * duration.
772                           */
773                         RCU_NONIDLE(armpmu_start(event, PERF_EF_RELOAD));
774                         break;
775                 default:
776                         break;
777                 }
778         }
779 }
780
781 static int cpu_pm_pmu_notify(struct notifier_block *b, unsigned long cmd,
782                              void *v)
783 {
784         struct arm_pmu *armpmu = container_of(b, struct arm_pmu, cpu_pm_nb);
785         struct pmu_hw_events *hw_events = this_cpu_ptr(armpmu->hw_events);
786         int enabled = bitmap_weight(hw_events->used_mask, armpmu->num_events);
787
788         if (!cpumask_test_cpu(smp_processor_id(), &armpmu->supported_cpus))
789                 return NOTIFY_DONE;
790
791         /*
792          * Always reset the PMU registers on power-up even if
793          * there are no events running.
794          */
795         if (cmd == CPU_PM_EXIT && armpmu->reset)
796                 armpmu->reset(armpmu);
797
798         if (!enabled)
799                 return NOTIFY_OK;
800
801         switch (cmd) {
802         case CPU_PM_ENTER:
803                 armpmu->stop(armpmu);
804                 cpu_pm_pmu_setup(armpmu, cmd);
805                 break;
806         case CPU_PM_EXIT:
807         case CPU_PM_ENTER_FAILED:
808                 cpu_pm_pmu_setup(armpmu, cmd);
809                 armpmu->start(armpmu);
810                 break;
811         default:
812                 return NOTIFY_DONE;
813         }
814
815         return NOTIFY_OK;
816 }
817
818 static int cpu_pm_pmu_register(struct arm_pmu *cpu_pmu)
819 {
820         cpu_pmu->cpu_pm_nb.notifier_call = cpu_pm_pmu_notify;
821         return cpu_pm_register_notifier(&cpu_pmu->cpu_pm_nb);
822 }
823
824 static void cpu_pm_pmu_unregister(struct arm_pmu *cpu_pmu)
825 {
826         cpu_pm_unregister_notifier(&cpu_pmu->cpu_pm_nb);
827 }
828 #else
829 static inline int cpu_pm_pmu_register(struct arm_pmu *cpu_pmu) { return 0; }
830 static inline void cpu_pm_pmu_unregister(struct arm_pmu *cpu_pmu) { }
831 #endif
832
833 static int cpu_pmu_init(struct arm_pmu *cpu_pmu)
834 {
835         int err;
836         int cpu;
837         struct pmu_hw_events __percpu *cpu_hw_events;
838
839         cpu_hw_events = alloc_percpu(struct pmu_hw_events);
840         if (!cpu_hw_events)
841                 return -ENOMEM;
842
843         err = cpuhp_state_add_instance_nocalls(CPUHP_AP_PERF_ARM_STARTING,
844                                                &cpu_pmu->node);
845         if (err)
846                 goto out_free;
847
848         err = cpu_pm_pmu_register(cpu_pmu);
849         if (err)
850                 goto out_unregister;
851
852         for_each_possible_cpu(cpu) {
853                 struct pmu_hw_events *events = per_cpu_ptr(cpu_hw_events, cpu);
854                 raw_spin_lock_init(&events->pmu_lock);
855                 events->percpu_pmu = cpu_pmu;
856         }
857
858         cpu_pmu->hw_events      = cpu_hw_events;
859         cpu_pmu->request_irq    = cpu_pmu_request_irq;
860         cpu_pmu->free_irq       = cpu_pmu_free_irq;
861
862         /* Ensure the PMU has sane values out of reset. */
863         if (cpu_pmu->reset)
864                 on_each_cpu_mask(&cpu_pmu->supported_cpus, cpu_pmu->reset,
865                          cpu_pmu, 1);
866
867         /* If no interrupts available, set the corresponding capability flag */
868         if (!platform_get_irq(cpu_pmu->plat_device, 0))
869                 cpu_pmu->pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
870
871         /*
872          * This is a CPU PMU potentially in a heterogeneous configuration (e.g.
873          * big.LITTLE). This is not an uncore PMU, and we have taken ctx
874          * sharing into account (e.g. with our pmu::filter_match callback and
875          * pmu::event_init group validation).
876          */
877         cpu_pmu->pmu.capabilities |= PERF_PMU_CAP_HETEROGENEOUS_CPUS;
878
879         return 0;
880
881 out_unregister:
882         cpuhp_state_remove_instance_nocalls(CPUHP_AP_PERF_ARM_STARTING,
883                                             &cpu_pmu->node);
884 out_free:
885         free_percpu(cpu_hw_events);
886         return err;
887 }
888
889 static void cpu_pmu_destroy(struct arm_pmu *cpu_pmu)
890 {
891         cpu_pm_pmu_unregister(cpu_pmu);
892         cpuhp_state_remove_instance_nocalls(CPUHP_AP_PERF_ARM_STARTING,
893                                             &cpu_pmu->node);
894         free_percpu(cpu_pmu->hw_events);
895 }
896
897 /*
898  * CPU PMU identification and probing.
899  */
900 static int probe_current_pmu(struct arm_pmu *pmu,
901                              const struct pmu_probe_info *info)
902 {
903         int cpu = get_cpu();
904         unsigned int cpuid = read_cpuid_id();
905         int ret = -ENODEV;
906
907         pr_info("probing PMU on CPU %d\n", cpu);
908
909         for (; info->init != NULL; info++) {
910                 if ((cpuid & info->mask) != info->cpuid)
911                         continue;
912                 ret = info->init(pmu);
913                 break;
914         }
915
916         put_cpu();
917         return ret;
918 }
919
920 static int of_pmu_irq_cfg(struct arm_pmu *pmu)
921 {
922         int *irqs, i = 0;
923         bool using_spi = false;
924         struct platform_device *pdev = pmu->plat_device;
925
926         irqs = kcalloc(pdev->num_resources, sizeof(*irqs), GFP_KERNEL);
927         if (!irqs)
928                 return -ENOMEM;
929
930         do {
931                 struct device_node *dn;
932                 int cpu, irq;
933
934                 /* See if we have an affinity entry */
935                 dn = of_parse_phandle(pdev->dev.of_node, "interrupt-affinity", i);
936                 if (!dn)
937                         break;
938
939                 /* Check the IRQ type and prohibit a mix of PPIs and SPIs */
940                 irq = platform_get_irq(pdev, i);
941                 if (irq > 0) {
942                         bool spi = !irq_is_percpu(irq);
943
944                         if (i > 0 && spi != using_spi) {
945                                 pr_err("PPI/SPI IRQ type mismatch for %s!\n",
946                                         dn->name);
947                                 of_node_put(dn);
948                                 kfree(irqs);
949                                 return -EINVAL;
950                         }
951
952                         using_spi = spi;
953                 }
954
955                 /* Now look up the logical CPU number */
956                 for_each_possible_cpu(cpu) {
957                         struct device_node *cpu_dn;
958
959                         cpu_dn = of_cpu_device_node_get(cpu);
960                         of_node_put(cpu_dn);
961
962                         if (dn == cpu_dn)
963                                 break;
964                 }
965
966                 if (cpu >= nr_cpu_ids) {
967                         pr_warn("Failed to find logical CPU for %s\n",
968                                 dn->name);
969                         of_node_put(dn);
970                         cpumask_setall(&pmu->supported_cpus);
971                         break;
972                 }
973                 of_node_put(dn);
974
975                 /* For SPIs, we need to track the affinity per IRQ */
976                 if (using_spi) {
977                         if (i >= pdev->num_resources)
978                                 break;
979
980                         irqs[i] = cpu;
981                 }
982
983                 /* Keep track of the CPUs containing this PMU type */
984                 cpumask_set_cpu(cpu, &pmu->supported_cpus);
985                 i++;
986         } while (1);
987
988         /* If we didn't manage to parse anything, try the interrupt affinity */
989         if (cpumask_weight(&pmu->supported_cpus) == 0) {
990                 int irq = platform_get_irq(pdev, 0);
991
992                 if (irq > 0 && irq_is_percpu(irq)) {
993                         /* If using PPIs, check the affinity of the partition */
994                         int ret;
995
996                         ret = irq_get_percpu_devid_partition(irq, &pmu->supported_cpus);
997                         if (ret) {
998                                 kfree(irqs);
999                                 return ret;
1000                         }
1001                 } else {
1002                         /* Otherwise default to all CPUs */
1003                         cpumask_setall(&pmu->supported_cpus);
1004                 }
1005         }
1006
1007         /* If we matched up the IRQ affinities, use them to route the SPIs */
1008         if (using_spi && i == pdev->num_resources)
1009                 pmu->irq_affinity = irqs;
1010         else
1011                 kfree(irqs);
1012
1013         return 0;
1014 }
1015
1016 int arm_pmu_device_probe(struct platform_device *pdev,
1017                          const struct of_device_id *of_table,
1018                          const struct pmu_probe_info *probe_table)
1019 {
1020         const struct of_device_id *of_id;
1021         const int (*init_fn)(struct arm_pmu *);
1022         struct device_node *node = pdev->dev.of_node;
1023         struct arm_pmu *pmu;
1024         int ret = -ENODEV;
1025
1026         pmu = kzalloc(sizeof(struct arm_pmu), GFP_KERNEL);
1027         if (!pmu) {
1028                 pr_info("failed to allocate PMU device!\n");
1029                 return -ENOMEM;
1030         }
1031
1032         armpmu_init(pmu);
1033
1034         pmu->plat_device = pdev;
1035
1036         if (node && (of_id = of_match_node(of_table, pdev->dev.of_node))) {
1037                 init_fn = of_id->data;
1038
1039                 pmu->secure_access = of_property_read_bool(pdev->dev.of_node,
1040                                                            "secure-reg-access");
1041
1042                 /* arm64 systems boot only as non-secure */
1043                 if (IS_ENABLED(CONFIG_ARM64) && pmu->secure_access) {
1044                         pr_warn("ignoring \"secure-reg-access\" property for arm64\n");
1045                         pmu->secure_access = false;
1046                 }
1047
1048                 ret = of_pmu_irq_cfg(pmu);
1049                 if (!ret)
1050                         ret = init_fn(pmu);
1051         } else if (probe_table) {
1052                 cpumask_setall(&pmu->supported_cpus);
1053                 ret = probe_current_pmu(pmu, probe_table);
1054         }
1055
1056         if (ret) {
1057                 pr_info("%s: failed to probe PMU!\n", of_node_full_name(node));
1058                 goto out_free;
1059         }
1060
1061
1062         ret = cpu_pmu_init(pmu);
1063         if (ret)
1064                 goto out_free;
1065
1066         ret = perf_pmu_register(&pmu->pmu, pmu->name, -1);
1067         if (ret)
1068                 goto out_destroy;
1069
1070         if (!__oprofile_cpu_pmu)
1071                 __oprofile_cpu_pmu = pmu;
1072
1073         pr_info("enabled with %s PMU driver, %d counters available\n",
1074                         pmu->name, pmu->num_events);
1075
1076         return 0;
1077
1078 out_destroy:
1079         cpu_pmu_destroy(pmu);
1080 out_free:
1081         pr_info("%s: failed to register PMU devices!\n",
1082                 of_node_full_name(node));
1083         kfree(pmu->irq_affinity);
1084         kfree(pmu);
1085         return ret;
1086 }
1087
1088 static int arm_pmu_hp_init(void)
1089 {
1090         int ret;
1091
1092         ret = cpuhp_setup_state_multi(CPUHP_AP_PERF_ARM_STARTING,
1093                                       "AP_PERF_ARM_STARTING",
1094                                       arm_perf_starting_cpu, NULL);
1095         if (ret)
1096                 pr_err("CPU hotplug notifier for ARM PMU could not be registered: %d\n",
1097                        ret);
1098         return ret;
1099 }
1100 subsys_initcall(arm_pmu_hp_init);