f1d3f47fc5830b4b0f84ac503070f71c8e9feb90
[platform/kernel/linux-starfive.git] / drivers / bus / arm-cci.c
1 /*
2  * CCI cache coherent interconnect driver
3  *
4  * Copyright (C) 2013 ARM Ltd.
5  * Author: Lorenzo Pieralisi <lorenzo.pieralisi@arm.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed "as is" WITHOUT ANY WARRANTY of any
12  * kind, whether express or implied; without even the implied warranty
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  */
16
17 #include <linux/arm-cci.h>
18 #include <linux/io.h>
19 #include <linux/interrupt.h>
20 #include <linux/module.h>
21 #include <linux/of_address.h>
22 #include <linux/of_irq.h>
23 #include <linux/of_platform.h>
24 #include <linux/perf_event.h>
25 #include <linux/platform_device.h>
26 #include <linux/slab.h>
27 #include <linux/spinlock.h>
28
29 #include <asm/cacheflush.h>
30 #include <asm/smp_plat.h>
31
32 static void __iomem *cci_ctrl_base;
33 static unsigned long cci_ctrl_phys;
34
35 #ifdef CONFIG_ARM_CCI400_PORT_CTRL
36 struct cci_nb_ports {
37         unsigned int nb_ace;
38         unsigned int nb_ace_lite;
39 };
40
41 static const struct cci_nb_ports cci400_ports = {
42         .nb_ace = 2,
43         .nb_ace_lite = 3
44 };
45
46 #define CCI400_PORTS_DATA       (&cci400_ports)
47 #else
48 #define CCI400_PORTS_DATA       (NULL)
49 #endif
50
51 static const struct of_device_id arm_cci_matches[] = {
52 #ifdef CONFIG_ARM_CCI400_COMMON
53         {.compatible = "arm,cci-400", .data = CCI400_PORTS_DATA },
54 #endif
55 #ifdef CONFIG_ARM_CCI500_PMU
56         { .compatible = "arm,cci-500", },
57 #endif
58         {},
59 };
60
61 #ifdef CONFIG_ARM_CCI_PMU
62
63 #define DRIVER_NAME             "ARM-CCI"
64 #define DRIVER_NAME_PMU         DRIVER_NAME " PMU"
65
66 #define CCI_PMCR                0x0100
67 #define CCI_PID2                0x0fe8
68
69 #define CCI_PMCR_CEN            0x00000001
70 #define CCI_PMCR_NCNT_MASK      0x0000f800
71 #define CCI_PMCR_NCNT_SHIFT     11
72
73 #define CCI_PID2_REV_MASK       0xf0
74 #define CCI_PID2_REV_SHIFT      4
75
76 #define CCI_PMU_EVT_SEL         0x000
77 #define CCI_PMU_CNTR            0x004
78 #define CCI_PMU_CNTR_CTRL       0x008
79 #define CCI_PMU_OVRFLW          0x00c
80
81 #define CCI_PMU_OVRFLW_FLAG     1
82
83 #define CCI_PMU_CNTR_SIZE(model)        ((model)->cntr_size)
84 #define CCI_PMU_CNTR_BASE(model, idx)   ((idx) * CCI_PMU_CNTR_SIZE(model))
85 #define CCI_PMU_CNTR_MASK               ((1ULL << 32) -1)
86 #define CCI_PMU_CNTR_LAST(cci_pmu)      (cci_pmu->num_cntrs - 1)
87
88 #define CCI_PMU_MAX_HW_CNTRS(model) \
89         ((model)->num_hw_cntrs + (model)->fixed_hw_cntrs)
90
91 /* Types of interfaces that can generate events */
92 enum {
93         CCI_IF_SLAVE,
94         CCI_IF_MASTER,
95 #ifdef CONFIG_ARM_CCI500_PMU
96         CCI_IF_GLOBAL,
97 #endif
98         CCI_IF_MAX,
99 };
100
101 struct event_range {
102         u32 min;
103         u32 max;
104 };
105
106 struct cci_pmu_hw_events {
107         struct perf_event **events;
108         unsigned long *used_mask;
109         raw_spinlock_t pmu_lock;
110 };
111
112 struct cci_pmu;
113 /*
114  * struct cci_pmu_model:
115  * @fixed_hw_cntrs - Number of fixed event counters
116  * @num_hw_cntrs - Maximum number of programmable event counters
117  * @cntr_size - Size of an event counter mapping
118  */
119 struct cci_pmu_model {
120         char *name;
121         u32 fixed_hw_cntrs;
122         u32 num_hw_cntrs;
123         u32 cntr_size;
124         struct attribute **format_attrs;
125         struct attribute **event_attrs;
126         struct event_range event_ranges[CCI_IF_MAX];
127         int (*validate_hw_event)(struct cci_pmu *, unsigned long);
128         int (*get_event_idx)(struct cci_pmu *, struct cci_pmu_hw_events *, unsigned long);
129         void (*write_counters)(struct cci_pmu *, unsigned long *);
130 };
131
132 static struct cci_pmu_model cci_pmu_models[];
133
134 struct cci_pmu {
135         void __iomem *base;
136         struct pmu pmu;
137         int nr_irqs;
138         int *irqs;
139         unsigned long active_irqs;
140         const struct cci_pmu_model *model;
141         struct cci_pmu_hw_events hw_events;
142         struct platform_device *plat_device;
143         int num_cntrs;
144         atomic_t active_events;
145         struct mutex reserve_mutex;
146         struct notifier_block cpu_nb;
147         cpumask_t cpus;
148 };
149
150 #define to_cci_pmu(c)   (container_of(c, struct cci_pmu, pmu))
151
152 enum cci_models {
153 #ifdef CONFIG_ARM_CCI400_PMU
154         CCI400_R0,
155         CCI400_R1,
156 #endif
157 #ifdef CONFIG_ARM_CCI500_PMU
158         CCI500_R0,
159 #endif
160         CCI_MODEL_MAX
161 };
162
163 static void pmu_write_counters(struct cci_pmu *cci_pmu,
164                                  unsigned long *mask);
165 static ssize_t cci_pmu_format_show(struct device *dev,
166                         struct device_attribute *attr, char *buf);
167 static ssize_t cci_pmu_event_show(struct device *dev,
168                         struct device_attribute *attr, char *buf);
169
170 #define CCI_EXT_ATTR_ENTRY(_name, _func, _config)                               \
171         &((struct dev_ext_attribute[]) {                                        \
172                 { __ATTR(_name, S_IRUGO, _func, NULL), (void *)_config }        \
173         })[0].attr.attr
174
175 #define CCI_FORMAT_EXT_ATTR_ENTRY(_name, _config) \
176         CCI_EXT_ATTR_ENTRY(_name, cci_pmu_format_show, (char *)_config)
177 #define CCI_EVENT_EXT_ATTR_ENTRY(_name, _config) \
178         CCI_EXT_ATTR_ENTRY(_name, cci_pmu_event_show, (unsigned long)_config)
179
180 /* CCI400 PMU Specific definitions */
181
182 #ifdef CONFIG_ARM_CCI400_PMU
183
184 /* Port ids */
185 #define CCI400_PORT_S0          0
186 #define CCI400_PORT_S1          1
187 #define CCI400_PORT_S2          2
188 #define CCI400_PORT_S3          3
189 #define CCI400_PORT_S4          4
190 #define CCI400_PORT_M0          5
191 #define CCI400_PORT_M1          6
192 #define CCI400_PORT_M2          7
193
194 #define CCI400_R1_PX            5
195
196 /*
197  * Instead of an event id to monitor CCI cycles, a dedicated counter is
198  * provided. Use 0xff to represent CCI cycles and hope that no future revisions
199  * make use of this event in hardware.
200  */
201 enum cci400_perf_events {
202         CCI400_PMU_CYCLES = 0xff
203 };
204
205 #define CCI400_PMU_CYCLE_CNTR_IDX       0
206 #define CCI400_PMU_CNTR0_IDX            1
207
208 /*
209  * CCI PMU event id is an 8-bit value made of two parts - bits 7:5 for one of 8
210  * ports and bits 4:0 are event codes. There are different event codes
211  * associated with each port type.
212  *
213  * Additionally, the range of events associated with the port types changed
214  * between Rev0 and Rev1.
215  *
216  * The constants below define the range of valid codes for each port type for
217  * the different revisions and are used to validate the event to be monitored.
218  */
219
220 #define CCI400_PMU_EVENT_MASK           0xffUL
221 #define CCI400_PMU_EVENT_SOURCE_SHIFT   5
222 #define CCI400_PMU_EVENT_SOURCE_MASK    0x7
223 #define CCI400_PMU_EVENT_CODE_SHIFT     0
224 #define CCI400_PMU_EVENT_CODE_MASK      0x1f
225 #define CCI400_PMU_EVENT_SOURCE(event) \
226         ((event >> CCI400_PMU_EVENT_SOURCE_SHIFT) & \
227                         CCI400_PMU_EVENT_SOURCE_MASK)
228 #define CCI400_PMU_EVENT_CODE(event) \
229         ((event >> CCI400_PMU_EVENT_CODE_SHIFT) & CCI400_PMU_EVENT_CODE_MASK)
230
231 #define CCI400_R0_SLAVE_PORT_MIN_EV     0x00
232 #define CCI400_R0_SLAVE_PORT_MAX_EV     0x13
233 #define CCI400_R0_MASTER_PORT_MIN_EV    0x14
234 #define CCI400_R0_MASTER_PORT_MAX_EV    0x1a
235
236 #define CCI400_R1_SLAVE_PORT_MIN_EV     0x00
237 #define CCI400_R1_SLAVE_PORT_MAX_EV     0x14
238 #define CCI400_R1_MASTER_PORT_MIN_EV    0x00
239 #define CCI400_R1_MASTER_PORT_MAX_EV    0x11
240
241 #define CCI400_CYCLE_EVENT_EXT_ATTR_ENTRY(_name, _config) \
242         CCI_EXT_ATTR_ENTRY(_name, cci400_pmu_cycle_event_show, \
243                                         (unsigned long)_config)
244
245 static ssize_t cci400_pmu_cycle_event_show(struct device *dev,
246                         struct device_attribute *attr, char *buf);
247
248 static struct attribute *cci400_pmu_format_attrs[] = {
249         CCI_FORMAT_EXT_ATTR_ENTRY(event, "config:0-4"),
250         CCI_FORMAT_EXT_ATTR_ENTRY(source, "config:5-7"),
251         NULL
252 };
253
254 static struct attribute *cci400_r0_pmu_event_attrs[] = {
255         /* Slave events */
256         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_any, 0x0),
257         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_device, 0x01),
258         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_normal_or_nonshareable, 0x2),
259         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_inner_or_outershareable, 0x3),
260         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_cache_maintenance, 0x4),
261         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_mem_barrier, 0x5),
262         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_sync_barrier, 0x6),
263         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_dvm_msg, 0x7),
264         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_dvm_msg_sync, 0x8),
265         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_stall_tt_full, 0x9),
266         CCI_EVENT_EXT_ATTR_ENTRY(si_r_data_last_hs_snoop, 0xA),
267         CCI_EVENT_EXT_ATTR_ENTRY(si_r_data_stall_rvalids_h_rready_l, 0xB),
268         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_any, 0xC),
269         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_device, 0xD),
270         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_normal_or_nonshareable, 0xE),
271         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_inner_or_outershare_wback_wclean, 0xF),
272         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_write_unique, 0x10),
273         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_write_line_unique, 0x11),
274         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_evict, 0x12),
275         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_stall_tt_full, 0x13),
276         /* Master events */
277         CCI_EVENT_EXT_ATTR_ENTRY(mi_retry_speculative_fetch, 0x14),
278         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_addr_hazard, 0x15),
279         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_id_hazard, 0x16),
280         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_tt_full, 0x17),
281         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_barrier_hazard, 0x18),
282         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_barrier_hazard, 0x19),
283         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_tt_full, 0x1A),
284         /* Special event for cycles counter */
285         CCI400_CYCLE_EVENT_EXT_ATTR_ENTRY(cycles, 0xff),
286         NULL
287 };
288
289 static struct attribute *cci400_r1_pmu_event_attrs[] = {
290         /* Slave events */
291         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_any, 0x0),
292         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_device, 0x01),
293         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_normal_or_nonshareable, 0x2),
294         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_inner_or_outershareable, 0x3),
295         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_cache_maintenance, 0x4),
296         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_mem_barrier, 0x5),
297         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_sync_barrier, 0x6),
298         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_dvm_msg, 0x7),
299         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_dvm_msg_sync, 0x8),
300         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_stall_tt_full, 0x9),
301         CCI_EVENT_EXT_ATTR_ENTRY(si_r_data_last_hs_snoop, 0xA),
302         CCI_EVENT_EXT_ATTR_ENTRY(si_r_data_stall_rvalids_h_rready_l, 0xB),
303         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_any, 0xC),
304         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_device, 0xD),
305         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_normal_or_nonshareable, 0xE),
306         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_inner_or_outershare_wback_wclean, 0xF),
307         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_write_unique, 0x10),
308         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_write_line_unique, 0x11),
309         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_evict, 0x12),
310         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_stall_tt_full, 0x13),
311         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_stall_slave_id_hazard, 0x14),
312         /* Master events */
313         CCI_EVENT_EXT_ATTR_ENTRY(mi_retry_speculative_fetch, 0x0),
314         CCI_EVENT_EXT_ATTR_ENTRY(mi_stall_cycle_addr_hazard, 0x1),
315         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_master_id_hazard, 0x2),
316         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_hi_prio_rtq_full, 0x3),
317         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_barrier_hazard, 0x4),
318         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_barrier_hazard, 0x5),
319         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_wtq_full, 0x6),
320         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_low_prio_rtq_full, 0x7),
321         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_mid_prio_rtq_full, 0x8),
322         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_qvn_vn0, 0x9),
323         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_qvn_vn1, 0xA),
324         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_qvn_vn2, 0xB),
325         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall_qvn_vn3, 0xC),
326         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_qvn_vn0, 0xD),
327         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_qvn_vn1, 0xE),
328         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_qvn_vn2, 0xF),
329         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall_qvn_vn3, 0x10),
330         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_unique_or_line_unique_addr_hazard, 0x11),
331         /* Special event for cycles counter */
332         CCI400_CYCLE_EVENT_EXT_ATTR_ENTRY(cycles, 0xff),
333         NULL
334 };
335
336 static ssize_t cci400_pmu_cycle_event_show(struct device *dev,
337                         struct device_attribute *attr, char *buf)
338 {
339         struct dev_ext_attribute *eattr = container_of(attr,
340                                 struct dev_ext_attribute, attr);
341         return snprintf(buf, PAGE_SIZE, "config=0x%lx\n", (unsigned long)eattr->var);
342 }
343
344 static int cci400_get_event_idx(struct cci_pmu *cci_pmu,
345                                 struct cci_pmu_hw_events *hw,
346                                 unsigned long cci_event)
347 {
348         int idx;
349
350         /* cycles event idx is fixed */
351         if (cci_event == CCI400_PMU_CYCLES) {
352                 if (test_and_set_bit(CCI400_PMU_CYCLE_CNTR_IDX, hw->used_mask))
353                         return -EAGAIN;
354
355                 return CCI400_PMU_CYCLE_CNTR_IDX;
356         }
357
358         for (idx = CCI400_PMU_CNTR0_IDX; idx <= CCI_PMU_CNTR_LAST(cci_pmu); ++idx)
359                 if (!test_and_set_bit(idx, hw->used_mask))
360                         return idx;
361
362         /* No counters available */
363         return -EAGAIN;
364 }
365
366 static int cci400_validate_hw_event(struct cci_pmu *cci_pmu, unsigned long hw_event)
367 {
368         u8 ev_source = CCI400_PMU_EVENT_SOURCE(hw_event);
369         u8 ev_code = CCI400_PMU_EVENT_CODE(hw_event);
370         int if_type;
371
372         if (hw_event & ~CCI400_PMU_EVENT_MASK)
373                 return -ENOENT;
374
375         if (hw_event == CCI400_PMU_CYCLES)
376                 return hw_event;
377
378         switch (ev_source) {
379         case CCI400_PORT_S0:
380         case CCI400_PORT_S1:
381         case CCI400_PORT_S2:
382         case CCI400_PORT_S3:
383         case CCI400_PORT_S4:
384                 /* Slave Interface */
385                 if_type = CCI_IF_SLAVE;
386                 break;
387         case CCI400_PORT_M0:
388         case CCI400_PORT_M1:
389         case CCI400_PORT_M2:
390                 /* Master Interface */
391                 if_type = CCI_IF_MASTER;
392                 break;
393         default:
394                 return -ENOENT;
395         }
396
397         if (ev_code >= cci_pmu->model->event_ranges[if_type].min &&
398                 ev_code <= cci_pmu->model->event_ranges[if_type].max)
399                 return hw_event;
400
401         return -ENOENT;
402 }
403
404 static int probe_cci400_revision(void)
405 {
406         int rev;
407         rev = readl_relaxed(cci_ctrl_base + CCI_PID2) & CCI_PID2_REV_MASK;
408         rev >>= CCI_PID2_REV_SHIFT;
409
410         if (rev < CCI400_R1_PX)
411                 return CCI400_R0;
412         else
413                 return CCI400_R1;
414 }
415
416 static const struct cci_pmu_model *probe_cci_model(struct platform_device *pdev)
417 {
418         if (platform_has_secure_cci_access())
419                 return &cci_pmu_models[probe_cci400_revision()];
420         return NULL;
421 }
422 #else   /* !CONFIG_ARM_CCI400_PMU */
423 static inline struct cci_pmu_model *probe_cci_model(struct platform_device *pdev)
424 {
425         return NULL;
426 }
427 #endif  /* CONFIG_ARM_CCI400_PMU */
428
429 #ifdef CONFIG_ARM_CCI500_PMU
430
431 /*
432  * CCI500 provides 8 independent event counters that can count
433  * any of the events available.
434  *
435  * CCI500 PMU event id is an 9-bit value made of two parts.
436  *       bits [8:5] - Source for the event
437  *                    0x0-0x6 - Slave interfaces
438  *                    0x8-0xD - Master interfaces
439  *                    0xf     - Global Events
440  *                    0x7,0xe - Reserved
441  *
442  *       bits [4:0] - Event code (specific to type of interface)
443  */
444
445 /* Port ids */
446 #define CCI500_PORT_S0                  0x0
447 #define CCI500_PORT_S1                  0x1
448 #define CCI500_PORT_S2                  0x2
449 #define CCI500_PORT_S3                  0x3
450 #define CCI500_PORT_S4                  0x4
451 #define CCI500_PORT_S5                  0x5
452 #define CCI500_PORT_S6                  0x6
453
454 #define CCI500_PORT_M0                  0x8
455 #define CCI500_PORT_M1                  0x9
456 #define CCI500_PORT_M2                  0xa
457 #define CCI500_PORT_M3                  0xb
458 #define CCI500_PORT_M4                  0xc
459 #define CCI500_PORT_M5                  0xd
460
461 #define CCI500_PORT_GLOBAL              0xf
462
463 #define CCI500_PMU_EVENT_MASK           0x1ffUL
464 #define CCI500_PMU_EVENT_SOURCE_SHIFT   0x5
465 #define CCI500_PMU_EVENT_SOURCE_MASK    0xf
466 #define CCI500_PMU_EVENT_CODE_SHIFT     0x0
467 #define CCI500_PMU_EVENT_CODE_MASK      0x1f
468
469 #define CCI500_PMU_EVENT_SOURCE(event)  \
470         ((event >> CCI500_PMU_EVENT_SOURCE_SHIFT) & CCI500_PMU_EVENT_SOURCE_MASK)
471 #define CCI500_PMU_EVENT_CODE(event)    \
472         ((event >> CCI500_PMU_EVENT_CODE_SHIFT) & CCI500_PMU_EVENT_CODE_MASK)
473
474 #define CCI500_SLAVE_PORT_MIN_EV        0x00
475 #define CCI500_SLAVE_PORT_MAX_EV        0x1f
476 #define CCI500_MASTER_PORT_MIN_EV       0x00
477 #define CCI500_MASTER_PORT_MAX_EV       0x06
478 #define CCI500_GLOBAL_PORT_MIN_EV       0x00
479 #define CCI500_GLOBAL_PORT_MAX_EV       0x0f
480
481
482 #define CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(_name, _config) \
483         CCI_EXT_ATTR_ENTRY(_name, cci500_pmu_global_event_show, \
484                                         (unsigned long) _config)
485
486 static ssize_t cci500_pmu_global_event_show(struct device *dev,
487                                 struct device_attribute *attr, char *buf);
488
489 static struct attribute *cci500_pmu_format_attrs[] = {
490         CCI_FORMAT_EXT_ATTR_ENTRY(event, "config:0-4"),
491         CCI_FORMAT_EXT_ATTR_ENTRY(source, "config:5-8"),
492         NULL,
493 };
494
495 static struct attribute *cci500_pmu_event_attrs[] = {
496         /* Slave events */
497         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_arvalid, 0x0),
498         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_dev, 0x1),
499         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_nonshareable, 0x2),
500         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_shareable_non_alloc, 0x3),
501         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_shareable_alloc, 0x4),
502         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_invalidate, 0x5),
503         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_cache_maint, 0x6),
504         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_dvm_msg, 0x7),
505         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_rval, 0x8),
506         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_hs_rlast_snoop, 0x9),
507         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_hs_awalid, 0xA),
508         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_dev, 0xB),
509         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_non_shareable, 0xC),
510         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_share_wb, 0xD),
511         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_share_wlu, 0xE),
512         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_share_wunique, 0xF),
513         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_evict, 0x10),
514         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_wrevict, 0x11),
515         CCI_EVENT_EXT_ATTR_ENTRY(si_w_data_beat, 0x12),
516         CCI_EVENT_EXT_ATTR_ENTRY(si_srq_acvalid, 0x13),
517         CCI_EVENT_EXT_ATTR_ENTRY(si_srq_read, 0x14),
518         CCI_EVENT_EXT_ATTR_ENTRY(si_srq_clean, 0x15),
519         CCI_EVENT_EXT_ATTR_ENTRY(si_srq_data_transfer_low, 0x16),
520         CCI_EVENT_EXT_ATTR_ENTRY(si_rrq_stall_arvalid, 0x17),
521         CCI_EVENT_EXT_ATTR_ENTRY(si_r_data_stall, 0x18),
522         CCI_EVENT_EXT_ATTR_ENTRY(si_wrq_stall, 0x19),
523         CCI_EVENT_EXT_ATTR_ENTRY(si_w_data_stall, 0x1A),
524         CCI_EVENT_EXT_ATTR_ENTRY(si_w_resp_stall, 0x1B),
525         CCI_EVENT_EXT_ATTR_ENTRY(si_srq_stall, 0x1C),
526         CCI_EVENT_EXT_ATTR_ENTRY(si_s_data_stall, 0x1D),
527         CCI_EVENT_EXT_ATTR_ENTRY(si_rq_stall_ot_limit, 0x1E),
528         CCI_EVENT_EXT_ATTR_ENTRY(si_r_stall_arbit, 0x1F),
529
530         /* Master events */
531         CCI_EVENT_EXT_ATTR_ENTRY(mi_r_data_beat_any, 0x0),
532         CCI_EVENT_EXT_ATTR_ENTRY(mi_w_data_beat_any, 0x1),
533         CCI_EVENT_EXT_ATTR_ENTRY(mi_rrq_stall, 0x2),
534         CCI_EVENT_EXT_ATTR_ENTRY(mi_r_data_stall, 0x3),
535         CCI_EVENT_EXT_ATTR_ENTRY(mi_wrq_stall, 0x4),
536         CCI_EVENT_EXT_ATTR_ENTRY(mi_w_data_stall, 0x5),
537         CCI_EVENT_EXT_ATTR_ENTRY(mi_w_resp_stall, 0x6),
538
539         /* Global events */
540         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_filter_bank_0_1, 0x0),
541         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_filter_bank_2_3, 0x1),
542         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_filter_bank_4_5, 0x2),
543         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_filter_bank_6_7, 0x3),
544         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_miss_filter_bank_0_1, 0x4),
545         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_miss_filter_bank_2_3, 0x5),
546         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_miss_filter_bank_4_5, 0x6),
547         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_access_miss_filter_bank_6_7, 0x7),
548         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_back_invalidation, 0x8),
549         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_stall_alloc_busy, 0x9),
550         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_stall_tt_full, 0xA),
551         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_wrq, 0xB),
552         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_cd_hs, 0xC),
553         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_rq_stall_addr_hazard, 0xD),
554         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snopp_rq_stall_tt_full, 0xE),
555         CCI500_GLOBAL_EVENT_EXT_ATTR_ENTRY(cci_snoop_rq_tzmp1_prot, 0xF),
556         NULL
557 };
558
559 static ssize_t cci500_pmu_global_event_show(struct device *dev,
560                                 struct device_attribute *attr, char *buf)
561 {
562         struct dev_ext_attribute *eattr = container_of(attr,
563                                         struct dev_ext_attribute, attr);
564         /* Global events have single fixed source code */
565         return snprintf(buf, PAGE_SIZE, "event=0x%lx,source=0x%x\n",
566                                 (unsigned long)eattr->var, CCI500_PORT_GLOBAL);
567 }
568
569 static int cci500_validate_hw_event(struct cci_pmu *cci_pmu,
570                                         unsigned long hw_event)
571 {
572         u32 ev_source = CCI500_PMU_EVENT_SOURCE(hw_event);
573         u32 ev_code = CCI500_PMU_EVENT_CODE(hw_event);
574         int if_type;
575
576         if (hw_event & ~CCI500_PMU_EVENT_MASK)
577                 return -ENOENT;
578
579         switch (ev_source) {
580         case CCI500_PORT_S0:
581         case CCI500_PORT_S1:
582         case CCI500_PORT_S2:
583         case CCI500_PORT_S3:
584         case CCI500_PORT_S4:
585         case CCI500_PORT_S5:
586         case CCI500_PORT_S6:
587                 if_type = CCI_IF_SLAVE;
588                 break;
589         case CCI500_PORT_M0:
590         case CCI500_PORT_M1:
591         case CCI500_PORT_M2:
592         case CCI500_PORT_M3:
593         case CCI500_PORT_M4:
594         case CCI500_PORT_M5:
595                 if_type = CCI_IF_MASTER;
596                 break;
597         case CCI500_PORT_GLOBAL:
598                 if_type = CCI_IF_GLOBAL;
599                 break;
600         default:
601                 return -ENOENT;
602         }
603
604         if (ev_code >= cci_pmu->model->event_ranges[if_type].min &&
605                 ev_code <= cci_pmu->model->event_ranges[if_type].max)
606                 return hw_event;
607
608         return -ENOENT;
609 }
610 #endif  /* CONFIG_ARM_CCI500_PMU */
611
612 /*
613  * Program the CCI PMU counters which have PERF_HES_ARCH set
614  * with the event period and mark them ready before we enable
615  * PMU.
616  */
617 void cci_pmu_sync_counters(struct cci_pmu *cci_pmu)
618 {
619         int i;
620         struct cci_pmu_hw_events *cci_hw = &cci_pmu->hw_events;
621
622         DECLARE_BITMAP(mask, cci_pmu->num_cntrs);
623
624         bitmap_zero(mask, cci_pmu->num_cntrs);
625         for_each_set_bit(i, cci_pmu->hw_events.used_mask, cci_pmu->num_cntrs) {
626                 struct perf_event *event = cci_hw->events[i];
627
628                 if (WARN_ON(!event))
629                         continue;
630
631                 /* Leave the events which are not counting */
632                 if (event->hw.state & PERF_HES_STOPPED)
633                         continue;
634                 if (event->hw.state & PERF_HES_ARCH) {
635                         set_bit(i, mask);
636                         event->hw.state &= ~PERF_HES_ARCH;
637                 }
638         }
639
640         pmu_write_counters(cci_pmu, mask);
641 }
642
643 /* Should be called with cci_pmu->hw_events->pmu_lock held */
644 static void __cci_pmu_enable_nosync(struct cci_pmu *cci_pmu)
645 {
646         u32 val;
647
648         /* Enable all the PMU counters. */
649         val = readl_relaxed(cci_ctrl_base + CCI_PMCR) | CCI_PMCR_CEN;
650         writel(val, cci_ctrl_base + CCI_PMCR);
651 }
652
653 /* Should be called with cci_pmu->hw_events->pmu_lock held */
654 static void __cci_pmu_enable_sync(struct cci_pmu *cci_pmu)
655 {
656         cci_pmu_sync_counters(cci_pmu);
657         __cci_pmu_enable_nosync(cci_pmu);
658 }
659
660 /* Should be called with cci_pmu->hw_events->pmu_lock held */
661 static void __cci_pmu_disable(void)
662 {
663         u32 val;
664
665         /* Disable all the PMU counters. */
666         val = readl_relaxed(cci_ctrl_base + CCI_PMCR) & ~CCI_PMCR_CEN;
667         writel(val, cci_ctrl_base + CCI_PMCR);
668 }
669
670 static ssize_t cci_pmu_format_show(struct device *dev,
671                         struct device_attribute *attr, char *buf)
672 {
673         struct dev_ext_attribute *eattr = container_of(attr,
674                                 struct dev_ext_attribute, attr);
675         return snprintf(buf, PAGE_SIZE, "%s\n", (char *)eattr->var);
676 }
677
678 static ssize_t cci_pmu_event_show(struct device *dev,
679                         struct device_attribute *attr, char *buf)
680 {
681         struct dev_ext_attribute *eattr = container_of(attr,
682                                 struct dev_ext_attribute, attr);
683         /* source parameter is mandatory for normal PMU events */
684         return snprintf(buf, PAGE_SIZE, "source=?,event=0x%lx\n",
685                                          (unsigned long)eattr->var);
686 }
687
688 static int pmu_is_valid_counter(struct cci_pmu *cci_pmu, int idx)
689 {
690         return 0 <= idx && idx <= CCI_PMU_CNTR_LAST(cci_pmu);
691 }
692
693 static u32 pmu_read_register(struct cci_pmu *cci_pmu, int idx, unsigned int offset)
694 {
695         return readl_relaxed(cci_pmu->base +
696                              CCI_PMU_CNTR_BASE(cci_pmu->model, idx) + offset);
697 }
698
699 static void pmu_write_register(struct cci_pmu *cci_pmu, u32 value,
700                                int idx, unsigned int offset)
701 {
702         return writel_relaxed(value, cci_pmu->base +
703                               CCI_PMU_CNTR_BASE(cci_pmu->model, idx) + offset);
704 }
705
706 static void pmu_disable_counter(struct cci_pmu *cci_pmu, int idx)
707 {
708         pmu_write_register(cci_pmu, 0, idx, CCI_PMU_CNTR_CTRL);
709 }
710
711 static void pmu_enable_counter(struct cci_pmu *cci_pmu, int idx)
712 {
713         pmu_write_register(cci_pmu, 1, idx, CCI_PMU_CNTR_CTRL);
714 }
715
716 static bool __maybe_unused
717 pmu_counter_is_enabled(struct cci_pmu *cci_pmu, int idx)
718 {
719         return (pmu_read_register(cci_pmu, idx, CCI_PMU_CNTR_CTRL) & 0x1) != 0;
720 }
721
722 static void pmu_set_event(struct cci_pmu *cci_pmu, int idx, unsigned long event)
723 {
724         pmu_write_register(cci_pmu, event, idx, CCI_PMU_EVT_SEL);
725 }
726
727 /*
728  * For all counters on the CCI-PMU, disable any 'enabled' counters,
729  * saving the changed counters in the mask, so that we can restore
730  * it later using pmu_restore_counters. The mask is private to the
731  * caller. We cannot rely on the used_mask maintained by the CCI_PMU
732  * as it only tells us if the counter is assigned to perf_event or not.
733  * The state of the perf_event cannot be locked by the PMU layer, hence
734  * we check the individual counter status (which can be locked by
735  * cci_pm->hw_events->pmu_lock).
736  *
737  * @mask should be initialised to empty by the caller.
738  */
739 static void __maybe_unused
740 pmu_save_counters(struct cci_pmu *cci_pmu, unsigned long *mask)
741 {
742         int i;
743
744         for (i = 0; i < cci_pmu->num_cntrs; i++) {
745                 if (pmu_counter_is_enabled(cci_pmu, i)) {
746                         set_bit(i, mask);
747                         pmu_disable_counter(cci_pmu, i);
748                 }
749         }
750 }
751
752 /*
753  * Restore the status of the counters. Reversal of the pmu_save_counters().
754  * For each counter set in the mask, enable the counter back.
755  */
756 static void __maybe_unused
757 pmu_restore_counters(struct cci_pmu *cci_pmu, unsigned long *mask)
758 {
759         int i;
760
761         for_each_set_bit(i, mask, cci_pmu->num_cntrs)
762                 pmu_enable_counter(cci_pmu, i);
763 }
764
765 /*
766  * Returns the number of programmable counters actually implemented
767  * by the cci
768  */
769 static u32 pmu_get_max_counters(void)
770 {
771         return (readl_relaxed(cci_ctrl_base + CCI_PMCR) &
772                 CCI_PMCR_NCNT_MASK) >> CCI_PMCR_NCNT_SHIFT;
773 }
774
775 static int pmu_get_event_idx(struct cci_pmu_hw_events *hw, struct perf_event *event)
776 {
777         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
778         unsigned long cci_event = event->hw.config_base;
779         int idx;
780
781         if (cci_pmu->model->get_event_idx)
782                 return cci_pmu->model->get_event_idx(cci_pmu, hw, cci_event);
783
784         /* Generic code to find an unused idx from the mask */
785         for(idx = 0; idx <= CCI_PMU_CNTR_LAST(cci_pmu); idx++)
786                 if (!test_and_set_bit(idx, hw->used_mask))
787                         return idx;
788
789         /* No counters available */
790         return -EAGAIN;
791 }
792
793 static int pmu_map_event(struct perf_event *event)
794 {
795         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
796
797         if (event->attr.type < PERF_TYPE_MAX ||
798                         !cci_pmu->model->validate_hw_event)
799                 return -ENOENT;
800
801         return  cci_pmu->model->validate_hw_event(cci_pmu, event->attr.config);
802 }
803
804 static int pmu_request_irq(struct cci_pmu *cci_pmu, irq_handler_t handler)
805 {
806         int i;
807         struct platform_device *pmu_device = cci_pmu->plat_device;
808
809         if (unlikely(!pmu_device))
810                 return -ENODEV;
811
812         if (cci_pmu->nr_irqs < 1) {
813                 dev_err(&pmu_device->dev, "no irqs for CCI PMUs defined\n");
814                 return -ENODEV;
815         }
816
817         /*
818          * Register all available CCI PMU interrupts. In the interrupt handler
819          * we iterate over the counters checking for interrupt source (the
820          * overflowing counter) and clear it.
821          *
822          * This should allow handling of non-unique interrupt for the counters.
823          */
824         for (i = 0; i < cci_pmu->nr_irqs; i++) {
825                 int err = request_irq(cci_pmu->irqs[i], handler, IRQF_SHARED,
826                                 "arm-cci-pmu", cci_pmu);
827                 if (err) {
828                         dev_err(&pmu_device->dev, "unable to request IRQ%d for ARM CCI PMU counters\n",
829                                 cci_pmu->irqs[i]);
830                         return err;
831                 }
832
833                 set_bit(i, &cci_pmu->active_irqs);
834         }
835
836         return 0;
837 }
838
839 static void pmu_free_irq(struct cci_pmu *cci_pmu)
840 {
841         int i;
842
843         for (i = 0; i < cci_pmu->nr_irqs; i++) {
844                 if (!test_and_clear_bit(i, &cci_pmu->active_irqs))
845                         continue;
846
847                 free_irq(cci_pmu->irqs[i], cci_pmu);
848         }
849 }
850
851 static u32 pmu_read_counter(struct perf_event *event)
852 {
853         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
854         struct hw_perf_event *hw_counter = &event->hw;
855         int idx = hw_counter->idx;
856         u32 value;
857
858         if (unlikely(!pmu_is_valid_counter(cci_pmu, idx))) {
859                 dev_err(&cci_pmu->plat_device->dev, "Invalid CCI PMU counter %d\n", idx);
860                 return 0;
861         }
862         value = pmu_read_register(cci_pmu, idx, CCI_PMU_CNTR);
863
864         return value;
865 }
866
867 static void pmu_write_counter(struct cci_pmu *cci_pmu, u32 value, int idx)
868 {
869         pmu_write_register(cci_pmu, value, idx, CCI_PMU_CNTR);
870 }
871
872 static void __pmu_write_counters(struct cci_pmu *cci_pmu, unsigned long *mask)
873 {
874         int i;
875         struct cci_pmu_hw_events *cci_hw = &cci_pmu->hw_events;
876
877         for_each_set_bit(i, mask, cci_pmu->num_cntrs) {
878                 struct perf_event *event = cci_hw->events[i];
879
880                 if (WARN_ON(!event))
881                         continue;
882                 pmu_write_counter(cci_pmu, local64_read(&event->hw.prev_count), i);
883         }
884 }
885
886 static void pmu_write_counters(struct cci_pmu *cci_pmu, unsigned long *mask)
887 {
888         if (cci_pmu->model->write_counters)
889                 cci_pmu->model->write_counters(cci_pmu, mask);
890         else
891                 __pmu_write_counters(cci_pmu, mask);
892 }
893
894 static u64 pmu_event_update(struct perf_event *event)
895 {
896         struct hw_perf_event *hwc = &event->hw;
897         u64 delta, prev_raw_count, new_raw_count;
898
899         do {
900                 prev_raw_count = local64_read(&hwc->prev_count);
901                 new_raw_count = pmu_read_counter(event);
902         } while (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
903                  new_raw_count) != prev_raw_count);
904
905         delta = (new_raw_count - prev_raw_count) & CCI_PMU_CNTR_MASK;
906
907         local64_add(delta, &event->count);
908
909         return new_raw_count;
910 }
911
912 static void pmu_read(struct perf_event *event)
913 {
914         pmu_event_update(event);
915 }
916
917 void pmu_event_set_period(struct perf_event *event)
918 {
919         struct hw_perf_event *hwc = &event->hw;
920         /*
921          * The CCI PMU counters have a period of 2^32. To account for the
922          * possiblity of extreme interrupt latency we program for a period of
923          * half that. Hopefully we can handle the interrupt before another 2^31
924          * events occur and the counter overtakes its previous value.
925          */
926         u64 val = 1ULL << 31;
927         local64_set(&hwc->prev_count, val);
928
929         /*
930          * CCI PMU uses PERF_HES_ARCH to keep track of the counters, whose
931          * values needs to be sync-ed with the s/w state before the PMU is
932          * enabled.
933          * Mark this counter for sync.
934          */
935         hwc->state |= PERF_HES_ARCH;
936 }
937
938 static irqreturn_t pmu_handle_irq(int irq_num, void *dev)
939 {
940         unsigned long flags;
941         struct cci_pmu *cci_pmu = dev;
942         struct cci_pmu_hw_events *events = &cci_pmu->hw_events;
943         int idx, handled = IRQ_NONE;
944
945         raw_spin_lock_irqsave(&events->pmu_lock, flags);
946
947         /* Disable the PMU while we walk through the counters */
948         __cci_pmu_disable();
949         /*
950          * Iterate over counters and update the corresponding perf events.
951          * This should work regardless of whether we have per-counter overflow
952          * interrupt or a combined overflow interrupt.
953          */
954         for (idx = 0; idx <= CCI_PMU_CNTR_LAST(cci_pmu); idx++) {
955                 struct perf_event *event = events->events[idx];
956                 struct hw_perf_event *hw_counter;
957
958                 if (!event)
959                         continue;
960
961                 hw_counter = &event->hw;
962
963                 /* Did this counter overflow? */
964                 if (!(pmu_read_register(cci_pmu, idx, CCI_PMU_OVRFLW) &
965                       CCI_PMU_OVRFLW_FLAG))
966                         continue;
967
968                 pmu_write_register(cci_pmu, CCI_PMU_OVRFLW_FLAG, idx,
969                                                         CCI_PMU_OVRFLW);
970
971                 pmu_event_update(event);
972                 pmu_event_set_period(event);
973                 handled = IRQ_HANDLED;
974         }
975
976         /* Enable the PMU and sync possibly overflowed counters */
977         __cci_pmu_enable_sync(cci_pmu);
978         raw_spin_unlock_irqrestore(&events->pmu_lock, flags);
979
980         return IRQ_RETVAL(handled);
981 }
982
983 static int cci_pmu_get_hw(struct cci_pmu *cci_pmu)
984 {
985         int ret = pmu_request_irq(cci_pmu, pmu_handle_irq);
986         if (ret) {
987                 pmu_free_irq(cci_pmu);
988                 return ret;
989         }
990         return 0;
991 }
992
993 static void cci_pmu_put_hw(struct cci_pmu *cci_pmu)
994 {
995         pmu_free_irq(cci_pmu);
996 }
997
998 static void hw_perf_event_destroy(struct perf_event *event)
999 {
1000         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
1001         atomic_t *active_events = &cci_pmu->active_events;
1002         struct mutex *reserve_mutex = &cci_pmu->reserve_mutex;
1003
1004         if (atomic_dec_and_mutex_lock(active_events, reserve_mutex)) {
1005                 cci_pmu_put_hw(cci_pmu);
1006                 mutex_unlock(reserve_mutex);
1007         }
1008 }
1009
1010 static void cci_pmu_enable(struct pmu *pmu)
1011 {
1012         struct cci_pmu *cci_pmu = to_cci_pmu(pmu);
1013         struct cci_pmu_hw_events *hw_events = &cci_pmu->hw_events;
1014         int enabled = bitmap_weight(hw_events->used_mask, cci_pmu->num_cntrs);
1015         unsigned long flags;
1016
1017         if (!enabled)
1018                 return;
1019
1020         raw_spin_lock_irqsave(&hw_events->pmu_lock, flags);
1021         __cci_pmu_enable_sync(cci_pmu);
1022         raw_spin_unlock_irqrestore(&hw_events->pmu_lock, flags);
1023
1024 }
1025
1026 static void cci_pmu_disable(struct pmu *pmu)
1027 {
1028         struct cci_pmu *cci_pmu = to_cci_pmu(pmu);
1029         struct cci_pmu_hw_events *hw_events = &cci_pmu->hw_events;
1030         unsigned long flags;
1031
1032         raw_spin_lock_irqsave(&hw_events->pmu_lock, flags);
1033         __cci_pmu_disable();
1034         raw_spin_unlock_irqrestore(&hw_events->pmu_lock, flags);
1035 }
1036
1037 /*
1038  * Check if the idx represents a non-programmable counter.
1039  * All the fixed event counters are mapped before the programmable
1040  * counters.
1041  */
1042 static bool pmu_fixed_hw_idx(struct cci_pmu *cci_pmu, int idx)
1043 {
1044         return (idx >= 0) && (idx < cci_pmu->model->fixed_hw_cntrs);
1045 }
1046
1047 static void cci_pmu_start(struct perf_event *event, int pmu_flags)
1048 {
1049         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
1050         struct cci_pmu_hw_events *hw_events = &cci_pmu->hw_events;
1051         struct hw_perf_event *hwc = &event->hw;
1052         int idx = hwc->idx;
1053         unsigned long flags;
1054
1055         /*
1056          * To handle interrupt latency, we always reprogram the period
1057          * regardlesss of PERF_EF_RELOAD.
1058          */
1059         if (pmu_flags & PERF_EF_RELOAD)
1060                 WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE));
1061
1062         hwc->state = 0;
1063
1064         if (unlikely(!pmu_is_valid_counter(cci_pmu, idx))) {
1065                 dev_err(&cci_pmu->plat_device->dev, "Invalid CCI PMU counter %d\n", idx);
1066                 return;
1067         }
1068
1069         raw_spin_lock_irqsave(&hw_events->pmu_lock, flags);
1070
1071         /* Configure the counter unless you are counting a fixed event */
1072         if (!pmu_fixed_hw_idx(cci_pmu, idx))
1073                 pmu_set_event(cci_pmu, idx, hwc->config_base);
1074
1075         pmu_event_set_period(event);
1076         pmu_enable_counter(cci_pmu, idx);
1077
1078         raw_spin_unlock_irqrestore(&hw_events->pmu_lock, flags);
1079 }
1080
1081 static void cci_pmu_stop(struct perf_event *event, int pmu_flags)
1082 {
1083         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
1084         struct hw_perf_event *hwc = &event->hw;
1085         int idx = hwc->idx;
1086
1087         if (hwc->state & PERF_HES_STOPPED)
1088                 return;
1089
1090         if (unlikely(!pmu_is_valid_counter(cci_pmu, idx))) {
1091                 dev_err(&cci_pmu->plat_device->dev, "Invalid CCI PMU counter %d\n", idx);
1092                 return;
1093         }
1094
1095         /*
1096          * We always reprogram the counter, so ignore PERF_EF_UPDATE. See
1097          * cci_pmu_start()
1098          */
1099         pmu_disable_counter(cci_pmu, idx);
1100         pmu_event_update(event);
1101         hwc->state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
1102 }
1103
1104 static int cci_pmu_add(struct perf_event *event, int flags)
1105 {
1106         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
1107         struct cci_pmu_hw_events *hw_events = &cci_pmu->hw_events;
1108         struct hw_perf_event *hwc = &event->hw;
1109         int idx;
1110         int err = 0;
1111
1112         perf_pmu_disable(event->pmu);
1113
1114         /* If we don't have a space for the counter then finish early. */
1115         idx = pmu_get_event_idx(hw_events, event);
1116         if (idx < 0) {
1117                 err = idx;
1118                 goto out;
1119         }
1120
1121         event->hw.idx = idx;
1122         hw_events->events[idx] = event;
1123
1124         hwc->state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
1125         if (flags & PERF_EF_START)
1126                 cci_pmu_start(event, PERF_EF_RELOAD);
1127
1128         /* Propagate our changes to the userspace mapping. */
1129         perf_event_update_userpage(event);
1130
1131 out:
1132         perf_pmu_enable(event->pmu);
1133         return err;
1134 }
1135
1136 static void cci_pmu_del(struct perf_event *event, int flags)
1137 {
1138         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
1139         struct cci_pmu_hw_events *hw_events = &cci_pmu->hw_events;
1140         struct hw_perf_event *hwc = &event->hw;
1141         int idx = hwc->idx;
1142
1143         cci_pmu_stop(event, PERF_EF_UPDATE);
1144         hw_events->events[idx] = NULL;
1145         clear_bit(idx, hw_events->used_mask);
1146
1147         perf_event_update_userpage(event);
1148 }
1149
1150 static int
1151 validate_event(struct pmu *cci_pmu,
1152                struct cci_pmu_hw_events *hw_events,
1153                struct perf_event *event)
1154 {
1155         if (is_software_event(event))
1156                 return 1;
1157
1158         /*
1159          * Reject groups spanning multiple HW PMUs (e.g. CPU + CCI). The
1160          * core perf code won't check that the pmu->ctx == leader->ctx
1161          * until after pmu->event_init(event).
1162          */
1163         if (event->pmu != cci_pmu)
1164                 return 0;
1165
1166         if (event->state < PERF_EVENT_STATE_OFF)
1167                 return 1;
1168
1169         if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
1170                 return 1;
1171
1172         return pmu_get_event_idx(hw_events, event) >= 0;
1173 }
1174
1175 static int
1176 validate_group(struct perf_event *event)
1177 {
1178         struct perf_event *sibling, *leader = event->group_leader;
1179         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
1180         unsigned long mask[BITS_TO_LONGS(cci_pmu->num_cntrs)];
1181         struct cci_pmu_hw_events fake_pmu = {
1182                 /*
1183                  * Initialise the fake PMU. We only need to populate the
1184                  * used_mask for the purposes of validation.
1185                  */
1186                 .used_mask = mask,
1187         };
1188         memset(mask, 0, BITS_TO_LONGS(cci_pmu->num_cntrs) * sizeof(unsigned long));
1189
1190         if (!validate_event(event->pmu, &fake_pmu, leader))
1191                 return -EINVAL;
1192
1193         list_for_each_entry(sibling, &leader->sibling_list, group_entry) {
1194                 if (!validate_event(event->pmu, &fake_pmu, sibling))
1195                         return -EINVAL;
1196         }
1197
1198         if (!validate_event(event->pmu, &fake_pmu, event))
1199                 return -EINVAL;
1200
1201         return 0;
1202 }
1203
1204 static int
1205 __hw_perf_event_init(struct perf_event *event)
1206 {
1207         struct hw_perf_event *hwc = &event->hw;
1208         int mapping;
1209
1210         mapping = pmu_map_event(event);
1211
1212         if (mapping < 0) {
1213                 pr_debug("event %x:%llx not supported\n", event->attr.type,
1214                          event->attr.config);
1215                 return mapping;
1216         }
1217
1218         /*
1219          * We don't assign an index until we actually place the event onto
1220          * hardware. Use -1 to signify that we haven't decided where to put it
1221          * yet.
1222          */
1223         hwc->idx                = -1;
1224         hwc->config_base        = 0;
1225         hwc->config             = 0;
1226         hwc->event_base         = 0;
1227
1228         /*
1229          * Store the event encoding into the config_base field.
1230          */
1231         hwc->config_base            |= (unsigned long)mapping;
1232
1233         /*
1234          * Limit the sample_period to half of the counter width. That way, the
1235          * new counter value is far less likely to overtake the previous one
1236          * unless you have some serious IRQ latency issues.
1237          */
1238         hwc->sample_period  = CCI_PMU_CNTR_MASK >> 1;
1239         hwc->last_period    = hwc->sample_period;
1240         local64_set(&hwc->period_left, hwc->sample_period);
1241
1242         if (event->group_leader != event) {
1243                 if (validate_group(event) != 0)
1244                         return -EINVAL;
1245         }
1246
1247         return 0;
1248 }
1249
1250 static int cci_pmu_event_init(struct perf_event *event)
1251 {
1252         struct cci_pmu *cci_pmu = to_cci_pmu(event->pmu);
1253         atomic_t *active_events = &cci_pmu->active_events;
1254         int err = 0;
1255         int cpu;
1256
1257         if (event->attr.type != event->pmu->type)
1258                 return -ENOENT;
1259
1260         /* Shared by all CPUs, no meaningful state to sample */
1261         if (is_sampling_event(event) || event->attach_state & PERF_ATTACH_TASK)
1262                 return -EOPNOTSUPP;
1263
1264         /* We have no filtering of any kind */
1265         if (event->attr.exclude_user    ||
1266             event->attr.exclude_kernel  ||
1267             event->attr.exclude_hv      ||
1268             event->attr.exclude_idle    ||
1269             event->attr.exclude_host    ||
1270             event->attr.exclude_guest)
1271                 return -EINVAL;
1272
1273         /*
1274          * Following the example set by other "uncore" PMUs, we accept any CPU
1275          * and rewrite its affinity dynamically rather than having perf core
1276          * handle cpu == -1 and pid == -1 for this case.
1277          *
1278          * The perf core will pin online CPUs for the duration of this call and
1279          * the event being installed into its context, so the PMU's CPU can't
1280          * change under our feet.
1281          */
1282         cpu = cpumask_first(&cci_pmu->cpus);
1283         if (event->cpu < 0 || cpu < 0)
1284                 return -EINVAL;
1285         event->cpu = cpu;
1286
1287         event->destroy = hw_perf_event_destroy;
1288         if (!atomic_inc_not_zero(active_events)) {
1289                 mutex_lock(&cci_pmu->reserve_mutex);
1290                 if (atomic_read(active_events) == 0)
1291                         err = cci_pmu_get_hw(cci_pmu);
1292                 if (!err)
1293                         atomic_inc(active_events);
1294                 mutex_unlock(&cci_pmu->reserve_mutex);
1295         }
1296         if (err)
1297                 return err;
1298
1299         err = __hw_perf_event_init(event);
1300         if (err)
1301                 hw_perf_event_destroy(event);
1302
1303         return err;
1304 }
1305
1306 static ssize_t pmu_cpumask_attr_show(struct device *dev,
1307                                      struct device_attribute *attr, char *buf)
1308 {
1309         struct pmu *pmu = dev_get_drvdata(dev);
1310         struct cci_pmu *cci_pmu = to_cci_pmu(pmu);
1311
1312         int n = scnprintf(buf, PAGE_SIZE - 1, "%*pbl",
1313                           cpumask_pr_args(&cci_pmu->cpus));
1314         buf[n++] = '\n';
1315         buf[n] = '\0';
1316         return n;
1317 }
1318
1319 static struct device_attribute pmu_cpumask_attr =
1320         __ATTR(cpumask, S_IRUGO, pmu_cpumask_attr_show, NULL);
1321
1322 static struct attribute *pmu_attrs[] = {
1323         &pmu_cpumask_attr.attr,
1324         NULL,
1325 };
1326
1327 static struct attribute_group pmu_attr_group = {
1328         .attrs = pmu_attrs,
1329 };
1330
1331 static struct attribute_group pmu_format_attr_group = {
1332         .name = "format",
1333         .attrs = NULL,          /* Filled in cci_pmu_init_attrs */
1334 };
1335
1336 static struct attribute_group pmu_event_attr_group = {
1337         .name = "events",
1338         .attrs = NULL,          /* Filled in cci_pmu_init_attrs */
1339 };
1340
1341 static const struct attribute_group *pmu_attr_groups[] = {
1342         &pmu_attr_group,
1343         &pmu_format_attr_group,
1344         &pmu_event_attr_group,
1345         NULL
1346 };
1347
1348 static int cci_pmu_init(struct cci_pmu *cci_pmu, struct platform_device *pdev)
1349 {
1350         const struct cci_pmu_model *model = cci_pmu->model;
1351         char *name = model->name;
1352         u32 num_cntrs;
1353
1354         pmu_event_attr_group.attrs = model->event_attrs;
1355         pmu_format_attr_group.attrs = model->format_attrs;
1356
1357         cci_pmu->pmu = (struct pmu) {
1358                 .name           = cci_pmu->model->name,
1359                 .task_ctx_nr    = perf_invalid_context,
1360                 .pmu_enable     = cci_pmu_enable,
1361                 .pmu_disable    = cci_pmu_disable,
1362                 .event_init     = cci_pmu_event_init,
1363                 .add            = cci_pmu_add,
1364                 .del            = cci_pmu_del,
1365                 .start          = cci_pmu_start,
1366                 .stop           = cci_pmu_stop,
1367                 .read           = pmu_read,
1368                 .attr_groups    = pmu_attr_groups,
1369         };
1370
1371         cci_pmu->plat_device = pdev;
1372         num_cntrs = pmu_get_max_counters();
1373         if (num_cntrs > cci_pmu->model->num_hw_cntrs) {
1374                 dev_warn(&pdev->dev,
1375                         "PMU implements more counters(%d) than supported by"
1376                         " the model(%d), truncated.",
1377                         num_cntrs, cci_pmu->model->num_hw_cntrs);
1378                 num_cntrs = cci_pmu->model->num_hw_cntrs;
1379         }
1380         cci_pmu->num_cntrs = num_cntrs + cci_pmu->model->fixed_hw_cntrs;
1381
1382         return perf_pmu_register(&cci_pmu->pmu, name, -1);
1383 }
1384
1385 static int cci_pmu_cpu_notifier(struct notifier_block *self,
1386                                 unsigned long action, void *hcpu)
1387 {
1388         struct cci_pmu *cci_pmu = container_of(self,
1389                                         struct cci_pmu, cpu_nb);
1390         unsigned int cpu = (long)hcpu;
1391         unsigned int target;
1392
1393         switch (action & ~CPU_TASKS_FROZEN) {
1394         case CPU_DOWN_PREPARE:
1395                 if (!cpumask_test_and_clear_cpu(cpu, &cci_pmu->cpus))
1396                         break;
1397                 target = cpumask_any_but(cpu_online_mask, cpu);
1398                 if (target >= nr_cpu_ids) // UP, last CPU
1399                         break;
1400                 /*
1401                  * TODO: migrate context once core races on event->ctx have
1402                  * been fixed.
1403                  */
1404                 cpumask_set_cpu(target, &cci_pmu->cpus);
1405         default:
1406                 break;
1407         }
1408
1409         return NOTIFY_OK;
1410 }
1411
1412 static struct cci_pmu_model cci_pmu_models[] = {
1413 #ifdef CONFIG_ARM_CCI400_PMU
1414         [CCI400_R0] = {
1415                 .name = "CCI_400",
1416                 .fixed_hw_cntrs = 1,    /* Cycle counter */
1417                 .num_hw_cntrs = 4,
1418                 .cntr_size = SZ_4K,
1419                 .format_attrs = cci400_pmu_format_attrs,
1420                 .event_attrs = cci400_r0_pmu_event_attrs,
1421                 .event_ranges = {
1422                         [CCI_IF_SLAVE] = {
1423                                 CCI400_R0_SLAVE_PORT_MIN_EV,
1424                                 CCI400_R0_SLAVE_PORT_MAX_EV,
1425                         },
1426                         [CCI_IF_MASTER] = {
1427                                 CCI400_R0_MASTER_PORT_MIN_EV,
1428                                 CCI400_R0_MASTER_PORT_MAX_EV,
1429                         },
1430                 },
1431                 .validate_hw_event = cci400_validate_hw_event,
1432                 .get_event_idx = cci400_get_event_idx,
1433         },
1434         [CCI400_R1] = {
1435                 .name = "CCI_400_r1",
1436                 .fixed_hw_cntrs = 1,    /* Cycle counter */
1437                 .num_hw_cntrs = 4,
1438                 .cntr_size = SZ_4K,
1439                 .format_attrs = cci400_pmu_format_attrs,
1440                 .event_attrs = cci400_r1_pmu_event_attrs,
1441                 .event_ranges = {
1442                         [CCI_IF_SLAVE] = {
1443                                 CCI400_R1_SLAVE_PORT_MIN_EV,
1444                                 CCI400_R1_SLAVE_PORT_MAX_EV,
1445                         },
1446                         [CCI_IF_MASTER] = {
1447                                 CCI400_R1_MASTER_PORT_MIN_EV,
1448                                 CCI400_R1_MASTER_PORT_MAX_EV,
1449                         },
1450                 },
1451                 .validate_hw_event = cci400_validate_hw_event,
1452                 .get_event_idx = cci400_get_event_idx,
1453         },
1454 #endif
1455 #ifdef CONFIG_ARM_CCI500_PMU
1456         [CCI500_R0] = {
1457                 .name = "CCI_500",
1458                 .fixed_hw_cntrs = 0,
1459                 .num_hw_cntrs = 8,
1460                 .cntr_size = SZ_64K,
1461                 .format_attrs = cci500_pmu_format_attrs,
1462                 .event_attrs = cci500_pmu_event_attrs,
1463                 .event_ranges = {
1464                         [CCI_IF_SLAVE] = {
1465                                 CCI500_SLAVE_PORT_MIN_EV,
1466                                 CCI500_SLAVE_PORT_MAX_EV,
1467                         },
1468                         [CCI_IF_MASTER] = {
1469                                 CCI500_MASTER_PORT_MIN_EV,
1470                                 CCI500_MASTER_PORT_MAX_EV,
1471                         },
1472                         [CCI_IF_GLOBAL] = {
1473                                 CCI500_GLOBAL_PORT_MIN_EV,
1474                                 CCI500_GLOBAL_PORT_MAX_EV,
1475                         },
1476                 },
1477                 .validate_hw_event = cci500_validate_hw_event,
1478         },
1479 #endif
1480 };
1481
1482 static const struct of_device_id arm_cci_pmu_matches[] = {
1483 #ifdef CONFIG_ARM_CCI400_PMU
1484         {
1485                 .compatible = "arm,cci-400-pmu",
1486                 .data   = NULL,
1487         },
1488         {
1489                 .compatible = "arm,cci-400-pmu,r0",
1490                 .data   = &cci_pmu_models[CCI400_R0],
1491         },
1492         {
1493                 .compatible = "arm,cci-400-pmu,r1",
1494                 .data   = &cci_pmu_models[CCI400_R1],
1495         },
1496 #endif
1497 #ifdef CONFIG_ARM_CCI500_PMU
1498         {
1499                 .compatible = "arm,cci-500-pmu,r0",
1500                 .data = &cci_pmu_models[CCI500_R0],
1501         },
1502 #endif
1503         {},
1504 };
1505
1506 static inline const struct cci_pmu_model *get_cci_model(struct platform_device *pdev)
1507 {
1508         const struct of_device_id *match = of_match_node(arm_cci_pmu_matches,
1509                                                         pdev->dev.of_node);
1510         if (!match)
1511                 return NULL;
1512         if (match->data)
1513                 return match->data;
1514
1515         dev_warn(&pdev->dev, "DEPRECATED compatible property,"
1516                          "requires secure access to CCI registers");
1517         return probe_cci_model(pdev);
1518 }
1519
1520 static bool is_duplicate_irq(int irq, int *irqs, int nr_irqs)
1521 {
1522         int i;
1523
1524         for (i = 0; i < nr_irqs; i++)
1525                 if (irq == irqs[i])
1526                         return true;
1527
1528         return false;
1529 }
1530
1531 static struct cci_pmu *cci_pmu_alloc(struct platform_device *pdev)
1532 {
1533         struct cci_pmu *cci_pmu;
1534         const struct cci_pmu_model *model;
1535
1536         /*
1537          * All allocations are devm_* hence we don't have to free
1538          * them explicitly on an error, as it would end up in driver
1539          * detach.
1540          */
1541         model = get_cci_model(pdev);
1542         if (!model) {
1543                 dev_warn(&pdev->dev, "CCI PMU version not supported\n");
1544                 return ERR_PTR(-ENODEV);
1545         }
1546
1547         cci_pmu = devm_kzalloc(&pdev->dev, sizeof(*cci_pmu), GFP_KERNEL);
1548         if (!cci_pmu)
1549                 return ERR_PTR(-ENOMEM);
1550
1551         cci_pmu->model = model;
1552         cci_pmu->irqs = devm_kcalloc(&pdev->dev, CCI_PMU_MAX_HW_CNTRS(model),
1553                                         sizeof(*cci_pmu->irqs), GFP_KERNEL);
1554         if (!cci_pmu->irqs)
1555                 return ERR_PTR(-ENOMEM);
1556         cci_pmu->hw_events.events = devm_kcalloc(&pdev->dev,
1557                                              CCI_PMU_MAX_HW_CNTRS(model),
1558                                              sizeof(*cci_pmu->hw_events.events),
1559                                              GFP_KERNEL);
1560         if (!cci_pmu->hw_events.events)
1561                 return ERR_PTR(-ENOMEM);
1562         cci_pmu->hw_events.used_mask = devm_kcalloc(&pdev->dev,
1563                                                 BITS_TO_LONGS(CCI_PMU_MAX_HW_CNTRS(model)),
1564                                                 sizeof(*cci_pmu->hw_events.used_mask),
1565                                                 GFP_KERNEL);
1566         if (!cci_pmu->hw_events.used_mask)
1567                 return ERR_PTR(-ENOMEM);
1568
1569         return cci_pmu;
1570 }
1571
1572
1573 static int cci_pmu_probe(struct platform_device *pdev)
1574 {
1575         struct resource *res;
1576         struct cci_pmu *cci_pmu;
1577         int i, ret, irq;
1578
1579         cci_pmu = cci_pmu_alloc(pdev);
1580         if (IS_ERR(cci_pmu))
1581                 return PTR_ERR(cci_pmu);
1582
1583         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1584         cci_pmu->base = devm_ioremap_resource(&pdev->dev, res);
1585         if (IS_ERR(cci_pmu->base))
1586                 return -ENOMEM;
1587
1588         /*
1589          * CCI PMU has one overflow interrupt per counter; but some may be tied
1590          * together to a common interrupt.
1591          */
1592         cci_pmu->nr_irqs = 0;
1593         for (i = 0; i < CCI_PMU_MAX_HW_CNTRS(cci_pmu->model); i++) {
1594                 irq = platform_get_irq(pdev, i);
1595                 if (irq < 0)
1596                         break;
1597
1598                 if (is_duplicate_irq(irq, cci_pmu->irqs, cci_pmu->nr_irqs))
1599                         continue;
1600
1601                 cci_pmu->irqs[cci_pmu->nr_irqs++] = irq;
1602         }
1603
1604         /*
1605          * Ensure that the device tree has as many interrupts as the number
1606          * of counters.
1607          */
1608         if (i < CCI_PMU_MAX_HW_CNTRS(cci_pmu->model)) {
1609                 dev_warn(&pdev->dev, "In-correct number of interrupts: %d, should be %d\n",
1610                         i, CCI_PMU_MAX_HW_CNTRS(cci_pmu->model));
1611                 return -EINVAL;
1612         }
1613
1614         raw_spin_lock_init(&cci_pmu->hw_events.pmu_lock);
1615         mutex_init(&cci_pmu->reserve_mutex);
1616         atomic_set(&cci_pmu->active_events, 0);
1617         cpumask_set_cpu(smp_processor_id(), &cci_pmu->cpus);
1618
1619         cci_pmu->cpu_nb = (struct notifier_block) {
1620                 .notifier_call  = cci_pmu_cpu_notifier,
1621                 /*
1622                  * to migrate uncore events, our notifier should be executed
1623                  * before perf core's notifier.
1624                  */
1625                 .priority       = CPU_PRI_PERF + 1,
1626         };
1627
1628         ret = register_cpu_notifier(&cci_pmu->cpu_nb);
1629         if (ret)
1630                 return ret;
1631
1632         ret = cci_pmu_init(cci_pmu, pdev);
1633         if (ret) {
1634                 unregister_cpu_notifier(&cci_pmu->cpu_nb);
1635                 return ret;
1636         }
1637
1638         pr_info("ARM %s PMU driver probed", cci_pmu->model->name);
1639         return 0;
1640 }
1641
1642 static int cci_platform_probe(struct platform_device *pdev)
1643 {
1644         if (!cci_probed())
1645                 return -ENODEV;
1646
1647         return of_platform_populate(pdev->dev.of_node, NULL, NULL, &pdev->dev);
1648 }
1649
1650 static struct platform_driver cci_pmu_driver = {
1651         .driver = {
1652                    .name = DRIVER_NAME_PMU,
1653                    .of_match_table = arm_cci_pmu_matches,
1654                   },
1655         .probe = cci_pmu_probe,
1656 };
1657
1658 static struct platform_driver cci_platform_driver = {
1659         .driver = {
1660                    .name = DRIVER_NAME,
1661                    .of_match_table = arm_cci_matches,
1662                   },
1663         .probe = cci_platform_probe,
1664 };
1665
1666 static int __init cci_platform_init(void)
1667 {
1668         int ret;
1669
1670         ret = platform_driver_register(&cci_pmu_driver);
1671         if (ret)
1672                 return ret;
1673
1674         return platform_driver_register(&cci_platform_driver);
1675 }
1676
1677 #else /* !CONFIG_ARM_CCI_PMU */
1678
1679 static int __init cci_platform_init(void)
1680 {
1681         return 0;
1682 }
1683
1684 #endif /* CONFIG_ARM_CCI_PMU */
1685
1686 #ifdef CONFIG_ARM_CCI400_PORT_CTRL
1687
1688 #define CCI_PORT_CTRL           0x0
1689 #define CCI_CTRL_STATUS         0xc
1690
1691 #define CCI_ENABLE_SNOOP_REQ    0x1
1692 #define CCI_ENABLE_DVM_REQ      0x2
1693 #define CCI_ENABLE_REQ          (CCI_ENABLE_SNOOP_REQ | CCI_ENABLE_DVM_REQ)
1694
1695 enum cci_ace_port_type {
1696         ACE_INVALID_PORT = 0x0,
1697         ACE_PORT,
1698         ACE_LITE_PORT,
1699 };
1700
1701 struct cci_ace_port {
1702         void __iomem *base;
1703         unsigned long phys;
1704         enum cci_ace_port_type type;
1705         struct device_node *dn;
1706 };
1707
1708 static struct cci_ace_port *ports;
1709 static unsigned int nb_cci_ports;
1710
1711 struct cpu_port {
1712         u64 mpidr;
1713         u32 port;
1714 };
1715
1716 /*
1717  * Use the port MSB as valid flag, shift can be made dynamic
1718  * by computing number of bits required for port indexes.
1719  * Code disabling CCI cpu ports runs with D-cache invalidated
1720  * and SCTLR bit clear so data accesses must be kept to a minimum
1721  * to improve performance; for now shift is left static to
1722  * avoid one more data access while disabling the CCI port.
1723  */
1724 #define PORT_VALID_SHIFT        31
1725 #define PORT_VALID              (0x1 << PORT_VALID_SHIFT)
1726
1727 static inline void init_cpu_port(struct cpu_port *port, u32 index, u64 mpidr)
1728 {
1729         port->port = PORT_VALID | index;
1730         port->mpidr = mpidr;
1731 }
1732
1733 static inline bool cpu_port_is_valid(struct cpu_port *port)
1734 {
1735         return !!(port->port & PORT_VALID);
1736 }
1737
1738 static inline bool cpu_port_match(struct cpu_port *port, u64 mpidr)
1739 {
1740         return port->mpidr == (mpidr & MPIDR_HWID_BITMASK);
1741 }
1742
1743 static struct cpu_port cpu_port[NR_CPUS];
1744
1745 /**
1746  * __cci_ace_get_port - Function to retrieve the port index connected to
1747  *                      a cpu or device.
1748  *
1749  * @dn: device node of the device to look-up
1750  * @type: port type
1751  *
1752  * Return value:
1753  *      - CCI port index if success
1754  *      - -ENODEV if failure
1755  */
1756 static int __cci_ace_get_port(struct device_node *dn, int type)
1757 {
1758         int i;
1759         bool ace_match;
1760         struct device_node *cci_portn;
1761
1762         cci_portn = of_parse_phandle(dn, "cci-control-port", 0);
1763         for (i = 0; i < nb_cci_ports; i++) {
1764                 ace_match = ports[i].type == type;
1765                 if (ace_match && cci_portn == ports[i].dn)
1766                         return i;
1767         }
1768         return -ENODEV;
1769 }
1770
1771 int cci_ace_get_port(struct device_node *dn)
1772 {
1773         return __cci_ace_get_port(dn, ACE_LITE_PORT);
1774 }
1775 EXPORT_SYMBOL_GPL(cci_ace_get_port);
1776
1777 static void cci_ace_init_ports(void)
1778 {
1779         int port, cpu;
1780         struct device_node *cpun;
1781
1782         /*
1783          * Port index look-up speeds up the function disabling ports by CPU,
1784          * since the logical to port index mapping is done once and does
1785          * not change after system boot.
1786          * The stashed index array is initialized for all possible CPUs
1787          * at probe time.
1788          */
1789         for_each_possible_cpu(cpu) {
1790                 /* too early to use cpu->of_node */
1791                 cpun = of_get_cpu_node(cpu, NULL);
1792
1793                 if (WARN(!cpun, "Missing cpu device node\n"))
1794                         continue;
1795
1796                 port = __cci_ace_get_port(cpun, ACE_PORT);
1797                 if (port < 0)
1798                         continue;
1799
1800                 init_cpu_port(&cpu_port[cpu], port, cpu_logical_map(cpu));
1801         }
1802
1803         for_each_possible_cpu(cpu) {
1804                 WARN(!cpu_port_is_valid(&cpu_port[cpu]),
1805                         "CPU %u does not have an associated CCI port\n",
1806                         cpu);
1807         }
1808 }
1809 /*
1810  * Functions to enable/disable a CCI interconnect slave port
1811  *
1812  * They are called by low-level power management code to disable slave
1813  * interfaces snoops and DVM broadcast.
1814  * Since they may execute with cache data allocation disabled and
1815  * after the caches have been cleaned and invalidated the functions provide
1816  * no explicit locking since they may run with D-cache disabled, so normal
1817  * cacheable kernel locks based on ldrex/strex may not work.
1818  * Locking has to be provided by BSP implementations to ensure proper
1819  * operations.
1820  */
1821
1822 /**
1823  * cci_port_control() - function to control a CCI port
1824  *
1825  * @port: index of the port to setup
1826  * @enable: if true enables the port, if false disables it
1827  */
1828 static void notrace cci_port_control(unsigned int port, bool enable)
1829 {
1830         void __iomem *base = ports[port].base;
1831
1832         writel_relaxed(enable ? CCI_ENABLE_REQ : 0, base + CCI_PORT_CTRL);
1833         /*
1834          * This function is called from power down procedures
1835          * and must not execute any instruction that might
1836          * cause the processor to be put in a quiescent state
1837          * (eg wfi). Hence, cpu_relax() can not be added to this
1838          * read loop to optimize power, since it might hide possibly
1839          * disruptive operations.
1840          */
1841         while (readl_relaxed(cci_ctrl_base + CCI_CTRL_STATUS) & 0x1)
1842                         ;
1843 }
1844
1845 /**
1846  * cci_disable_port_by_cpu() - function to disable a CCI port by CPU
1847  *                             reference
1848  *
1849  * @mpidr: mpidr of the CPU whose CCI port should be disabled
1850  *
1851  * Disabling a CCI port for a CPU implies disabling the CCI port
1852  * controlling that CPU cluster. Code disabling CPU CCI ports
1853  * must make sure that the CPU running the code is the last active CPU
1854  * in the cluster ie all other CPUs are quiescent in a low power state.
1855  *
1856  * Return:
1857  *      0 on success
1858  *      -ENODEV on port look-up failure
1859  */
1860 int notrace cci_disable_port_by_cpu(u64 mpidr)
1861 {
1862         int cpu;
1863         bool is_valid;
1864         for (cpu = 0; cpu < nr_cpu_ids; cpu++) {
1865                 is_valid = cpu_port_is_valid(&cpu_port[cpu]);
1866                 if (is_valid && cpu_port_match(&cpu_port[cpu], mpidr)) {
1867                         cci_port_control(cpu_port[cpu].port, false);
1868                         return 0;
1869                 }
1870         }
1871         return -ENODEV;
1872 }
1873 EXPORT_SYMBOL_GPL(cci_disable_port_by_cpu);
1874
1875 /**
1876  * cci_enable_port_for_self() - enable a CCI port for calling CPU
1877  *
1878  * Enabling a CCI port for the calling CPU implies enabling the CCI
1879  * port controlling that CPU's cluster. Caller must make sure that the
1880  * CPU running the code is the first active CPU in the cluster and all
1881  * other CPUs are quiescent in a low power state  or waiting for this CPU
1882  * to complete the CCI initialization.
1883  *
1884  * Because this is called when the MMU is still off and with no stack,
1885  * the code must be position independent and ideally rely on callee
1886  * clobbered registers only.  To achieve this we must code this function
1887  * entirely in assembler.
1888  *
1889  * On success this returns with the proper CCI port enabled.  In case of
1890  * any failure this never returns as the inability to enable the CCI is
1891  * fatal and there is no possible recovery at this stage.
1892  */
1893 asmlinkage void __naked cci_enable_port_for_self(void)
1894 {
1895         asm volatile ("\n"
1896 "       .arch armv7-a\n"
1897 "       mrc     p15, 0, r0, c0, c0, 5   @ get MPIDR value \n"
1898 "       and     r0, r0, #"__stringify(MPIDR_HWID_BITMASK)" \n"
1899 "       adr     r1, 5f \n"
1900 "       ldr     r2, [r1] \n"
1901 "       add     r1, r1, r2              @ &cpu_port \n"
1902 "       add     ip, r1, %[sizeof_cpu_port] \n"
1903
1904         /* Loop over the cpu_port array looking for a matching MPIDR */
1905 "1:     ldr     r2, [r1, %[offsetof_cpu_port_mpidr_lsb]] \n"
1906 "       cmp     r2, r0                  @ compare MPIDR \n"
1907 "       bne     2f \n"
1908
1909         /* Found a match, now test port validity */
1910 "       ldr     r3, [r1, %[offsetof_cpu_port_port]] \n"
1911 "       tst     r3, #"__stringify(PORT_VALID)" \n"
1912 "       bne     3f \n"
1913
1914         /* no match, loop with the next cpu_port entry */
1915 "2:     add     r1, r1, %[sizeof_struct_cpu_port] \n"
1916 "       cmp     r1, ip                  @ done? \n"
1917 "       blo     1b \n"
1918
1919         /* CCI port not found -- cheaply try to stall this CPU */
1920 "cci_port_not_found: \n"
1921 "       wfi \n"
1922 "       wfe \n"
1923 "       b       cci_port_not_found \n"
1924
1925         /* Use matched port index to look up the corresponding ports entry */
1926 "3:     bic     r3, r3, #"__stringify(PORT_VALID)" \n"
1927 "       adr     r0, 6f \n"
1928 "       ldmia   r0, {r1, r2} \n"
1929 "       sub     r1, r1, r0              @ virt - phys \n"
1930 "       ldr     r0, [r0, r2]            @ *(&ports) \n"
1931 "       mov     r2, %[sizeof_struct_ace_port] \n"
1932 "       mla     r0, r2, r3, r0          @ &ports[index] \n"
1933 "       sub     r0, r0, r1              @ virt_to_phys() \n"
1934
1935         /* Enable the CCI port */
1936 "       ldr     r0, [r0, %[offsetof_port_phys]] \n"
1937 "       mov     r3, %[cci_enable_req]\n"                   
1938 "       str     r3, [r0, #"__stringify(CCI_PORT_CTRL)"] \n"
1939
1940         /* poll the status reg for completion */
1941 "       adr     r1, 7f \n"
1942 "       ldr     r0, [r1] \n"
1943 "       ldr     r0, [r0, r1]            @ cci_ctrl_base \n"
1944 "4:     ldr     r1, [r0, #"__stringify(CCI_CTRL_STATUS)"] \n"
1945 "       tst     r1, %[cci_control_status_bits] \n"                      
1946 "       bne     4b \n"
1947
1948 "       mov     r0, #0 \n"
1949 "       bx      lr \n"
1950
1951 "       .align  2 \n"
1952 "5:     .word   cpu_port - . \n"
1953 "6:     .word   . \n"
1954 "       .word   ports - 6b \n"
1955 "7:     .word   cci_ctrl_phys - . \n"
1956         : :
1957         [sizeof_cpu_port] "i" (sizeof(cpu_port)),
1958         [cci_enable_req] "i" cpu_to_le32(CCI_ENABLE_REQ),
1959         [cci_control_status_bits] "i" cpu_to_le32(1),
1960 #ifndef __ARMEB__
1961         [offsetof_cpu_port_mpidr_lsb] "i" (offsetof(struct cpu_port, mpidr)),
1962 #else
1963         [offsetof_cpu_port_mpidr_lsb] "i" (offsetof(struct cpu_port, mpidr)+4),
1964 #endif
1965         [offsetof_cpu_port_port] "i" (offsetof(struct cpu_port, port)),
1966         [sizeof_struct_cpu_port] "i" (sizeof(struct cpu_port)),
1967         [sizeof_struct_ace_port] "i" (sizeof(struct cci_ace_port)),
1968         [offsetof_port_phys] "i" (offsetof(struct cci_ace_port, phys)) );
1969
1970         unreachable();
1971 }
1972
1973 /**
1974  * __cci_control_port_by_device() - function to control a CCI port by device
1975  *                                  reference
1976  *
1977  * @dn: device node pointer of the device whose CCI port should be
1978  *      controlled
1979  * @enable: if true enables the port, if false disables it
1980  *
1981  * Return:
1982  *      0 on success
1983  *      -ENODEV on port look-up failure
1984  */
1985 int notrace __cci_control_port_by_device(struct device_node *dn, bool enable)
1986 {
1987         int port;
1988
1989         if (!dn)
1990                 return -ENODEV;
1991
1992         port = __cci_ace_get_port(dn, ACE_LITE_PORT);
1993         if (WARN_ONCE(port < 0, "node %s ACE lite port look-up failure\n",
1994                                 dn->full_name))
1995                 return -ENODEV;
1996         cci_port_control(port, enable);
1997         return 0;
1998 }
1999 EXPORT_SYMBOL_GPL(__cci_control_port_by_device);
2000
2001 /**
2002  * __cci_control_port_by_index() - function to control a CCI port by port index
2003  *
2004  * @port: port index previously retrieved with cci_ace_get_port()
2005  * @enable: if true enables the port, if false disables it
2006  *
2007  * Return:
2008  *      0 on success
2009  *      -ENODEV on port index out of range
2010  *      -EPERM if operation carried out on an ACE PORT
2011  */
2012 int notrace __cci_control_port_by_index(u32 port, bool enable)
2013 {
2014         if (port >= nb_cci_ports || ports[port].type == ACE_INVALID_PORT)
2015                 return -ENODEV;
2016         /*
2017          * CCI control for ports connected to CPUS is extremely fragile
2018          * and must be made to go through a specific and controlled
2019          * interface (ie cci_disable_port_by_cpu(); control by general purpose
2020          * indexing is therefore disabled for ACE ports.
2021          */
2022         if (ports[port].type == ACE_PORT)
2023                 return -EPERM;
2024
2025         cci_port_control(port, enable);
2026         return 0;
2027 }
2028 EXPORT_SYMBOL_GPL(__cci_control_port_by_index);
2029
2030 static const struct of_device_id arm_cci_ctrl_if_matches[] = {
2031         {.compatible = "arm,cci-400-ctrl-if", },
2032         {},
2033 };
2034
2035 static int cci_probe_ports(struct device_node *np)
2036 {
2037         struct cci_nb_ports const *cci_config;
2038         int ret, i, nb_ace = 0, nb_ace_lite = 0;
2039         struct device_node *cp;
2040         struct resource res;
2041         const char *match_str;
2042         bool is_ace;
2043
2044
2045         cci_config = of_match_node(arm_cci_matches, np)->data;
2046         if (!cci_config)
2047                 return -ENODEV;
2048
2049         nb_cci_ports = cci_config->nb_ace + cci_config->nb_ace_lite;
2050
2051         ports = kcalloc(nb_cci_ports, sizeof(*ports), GFP_KERNEL);
2052         if (!ports)
2053                 return -ENOMEM;
2054
2055         for_each_child_of_node(np, cp) {
2056                 if (!of_match_node(arm_cci_ctrl_if_matches, cp))
2057                         continue;
2058
2059                 i = nb_ace + nb_ace_lite;
2060
2061                 if (i >= nb_cci_ports)
2062                         break;
2063
2064                 if (of_property_read_string(cp, "interface-type",
2065                                         &match_str)) {
2066                         WARN(1, "node %s missing interface-type property\n",
2067                                   cp->full_name);
2068                         continue;
2069                 }
2070                 is_ace = strcmp(match_str, "ace") == 0;
2071                 if (!is_ace && strcmp(match_str, "ace-lite")) {
2072                         WARN(1, "node %s containing invalid interface-type property, skipping it\n",
2073                                         cp->full_name);
2074                         continue;
2075                 }
2076
2077                 ret = of_address_to_resource(cp, 0, &res);
2078                 if (!ret) {
2079                         ports[i].base = ioremap(res.start, resource_size(&res));
2080                         ports[i].phys = res.start;
2081                 }
2082                 if (ret || !ports[i].base) {
2083                         WARN(1, "unable to ioremap CCI port %d\n", i);
2084                         continue;
2085                 }
2086
2087                 if (is_ace) {
2088                         if (WARN_ON(nb_ace >= cci_config->nb_ace))
2089                                 continue;
2090                         ports[i].type = ACE_PORT;
2091                         ++nb_ace;
2092                 } else {
2093                         if (WARN_ON(nb_ace_lite >= cci_config->nb_ace_lite))
2094                                 continue;
2095                         ports[i].type = ACE_LITE_PORT;
2096                         ++nb_ace_lite;
2097                 }
2098                 ports[i].dn = cp;
2099         }
2100
2101          /* initialize a stashed array of ACE ports to speed-up look-up */
2102         cci_ace_init_ports();
2103
2104         /*
2105          * Multi-cluster systems may need this data when non-coherent, during
2106          * cluster power-up/power-down. Make sure it reaches main memory.
2107          */
2108         sync_cache_w(&cci_ctrl_base);
2109         sync_cache_w(&cci_ctrl_phys);
2110         sync_cache_w(&ports);
2111         sync_cache_w(&cpu_port);
2112         __sync_cache_range_w(ports, sizeof(*ports) * nb_cci_ports);
2113         pr_info("ARM CCI driver probed\n");
2114
2115         return 0;
2116 }
2117 #else /* !CONFIG_ARM_CCI400_PORT_CTRL */
2118 static inline int cci_probe_ports(struct device_node *np)
2119 {
2120         return 0;
2121 }
2122 #endif /* CONFIG_ARM_CCI400_PORT_CTRL */
2123
2124 static int cci_probe(void)
2125 {
2126         int ret;
2127         struct device_node *np;
2128         struct resource res;
2129
2130         np = of_find_matching_node(NULL, arm_cci_matches);
2131         if(!np || !of_device_is_available(np))
2132                 return -ENODEV;
2133
2134         ret = of_address_to_resource(np, 0, &res);
2135         if (!ret) {
2136                 cci_ctrl_base = ioremap(res.start, resource_size(&res));
2137                 cci_ctrl_phys = res.start;
2138         }
2139         if (ret || !cci_ctrl_base) {
2140                 WARN(1, "unable to ioremap CCI ctrl\n");
2141                 return -ENXIO;
2142         }
2143
2144         return cci_probe_ports(np);
2145 }
2146
2147 static int cci_init_status = -EAGAIN;
2148 static DEFINE_MUTEX(cci_probing);
2149
2150 static int cci_init(void)
2151 {
2152         if (cci_init_status != -EAGAIN)
2153                 return cci_init_status;
2154
2155         mutex_lock(&cci_probing);
2156         if (cci_init_status == -EAGAIN)
2157                 cci_init_status = cci_probe();
2158         mutex_unlock(&cci_probing);
2159         return cci_init_status;
2160 }
2161
2162 /*
2163  * To sort out early init calls ordering a helper function is provided to
2164  * check if the CCI driver has beed initialized. Function check if the driver
2165  * has been initialized, if not it calls the init function that probes
2166  * the driver and updates the return value.
2167  */
2168 bool cci_probed(void)
2169 {
2170         return cci_init() == 0;
2171 }
2172 EXPORT_SYMBOL_GPL(cci_probed);
2173
2174 early_initcall(cci_init);
2175 core_initcall(cci_platform_init);
2176 MODULE_LICENSE("GPL");
2177 MODULE_DESCRIPTION("ARM CCI support");