Linux-libre 4.14.69-gnu
[librecmc/linux-libre.git] / arch / powerpc / perf / imc-pmu.c
1 /*
2  * In-Memory Collection (IMC) Performance Monitor counter support.
3  *
4  * Copyright (C) 2017 Madhavan Srinivasan, IBM Corporation.
5  *           (C) 2017 Anju T Sudhakar, IBM Corporation.
6  *           (C) 2017 Hemant K Shaw, IBM Corporation.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version
11  * 2 of the License, or later version.
12  */
13 #include <linux/perf_event.h>
14 #include <linux/slab.h>
15 #include <asm/opal.h>
16 #include <asm/imc-pmu.h>
17 #include <asm/cputhreads.h>
18 #include <asm/smp.h>
19 #include <linux/string.h>
20
21 /* Nest IMC data structures and variables */
22
23 /*
24  * Used to avoid races in counting the nest-pmu units during hotplug
25  * register and unregister
26  */
27 static DEFINE_MUTEX(nest_init_lock);
28 static DEFINE_PER_CPU(struct imc_pmu_ref *, local_nest_imc_refc);
29 static struct imc_pmu *per_nest_pmu_arr[IMC_MAX_PMUS];
30 static cpumask_t nest_imc_cpumask;
31 struct imc_pmu_ref *nest_imc_refc;
32 static int nest_pmus;
33
34 /* Core IMC data structures and variables */
35
36 static cpumask_t core_imc_cpumask;
37 struct imc_pmu_ref *core_imc_refc;
38 static struct imc_pmu *core_imc_pmu;
39
40 /* Thread IMC data structures and variables */
41
42 static DEFINE_PER_CPU(u64 *, thread_imc_mem);
43 static struct imc_pmu *thread_imc_pmu;
44 static int thread_imc_mem_size;
45
46 struct imc_pmu *imc_event_to_pmu(struct perf_event *event)
47 {
48         return container_of(event->pmu, struct imc_pmu, pmu);
49 }
50
51 PMU_FORMAT_ATTR(event, "config:0-40");
52 PMU_FORMAT_ATTR(offset, "config:0-31");
53 PMU_FORMAT_ATTR(rvalue, "config:32");
54 PMU_FORMAT_ATTR(mode, "config:33-40");
55 static struct attribute *imc_format_attrs[] = {
56         &format_attr_event.attr,
57         &format_attr_offset.attr,
58         &format_attr_rvalue.attr,
59         &format_attr_mode.attr,
60         NULL,
61 };
62
63 static struct attribute_group imc_format_group = {
64         .name = "format",
65         .attrs = imc_format_attrs,
66 };
67
68 /* Get the cpumask printed to a buffer "buf" */
69 static ssize_t imc_pmu_cpumask_get_attr(struct device *dev,
70                                         struct device_attribute *attr,
71                                         char *buf)
72 {
73         struct pmu *pmu = dev_get_drvdata(dev);
74         struct imc_pmu *imc_pmu = container_of(pmu, struct imc_pmu, pmu);
75         cpumask_t *active_mask;
76
77         switch(imc_pmu->domain){
78         case IMC_DOMAIN_NEST:
79                 active_mask = &nest_imc_cpumask;
80                 break;
81         case IMC_DOMAIN_CORE:
82                 active_mask = &core_imc_cpumask;
83                 break;
84         default:
85                 return 0;
86         }
87
88         return cpumap_print_to_pagebuf(true, buf, active_mask);
89 }
90
91 static DEVICE_ATTR(cpumask, S_IRUGO, imc_pmu_cpumask_get_attr, NULL);
92
93 static struct attribute *imc_pmu_cpumask_attrs[] = {
94         &dev_attr_cpumask.attr,
95         NULL,
96 };
97
98 static struct attribute_group imc_pmu_cpumask_attr_group = {
99         .attrs = imc_pmu_cpumask_attrs,
100 };
101
102 /* device_str_attr_create : Populate event "name" and string "str" in attribute */
103 static struct attribute *device_str_attr_create(const char *name, const char *str)
104 {
105         struct perf_pmu_events_attr *attr;
106
107         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
108         if (!attr)
109                 return NULL;
110         sysfs_attr_init(&attr->attr.attr);
111
112         attr->event_str = str;
113         attr->attr.attr.name = name;
114         attr->attr.attr.mode = 0444;
115         attr->attr.show = perf_event_sysfs_show;
116
117         return &attr->attr.attr;
118 }
119
120 struct imc_events *imc_parse_event(struct device_node *np, const char *scale,
121                                   const char *unit, const char *prefix, u32 base)
122 {
123         struct imc_events *event;
124         const char *s;
125         u32 reg;
126
127         event = kzalloc(sizeof(struct imc_events), GFP_KERNEL);
128         if (!event)
129                 return NULL;
130
131         if (of_property_read_u32(np, "reg", &reg))
132                 goto error;
133         /* Add the base_reg value to the "reg" */
134         event->value = base + reg;
135
136         if (of_property_read_string(np, "event-name", &s))
137                 goto error;
138
139         event->name = kasprintf(GFP_KERNEL, "%s%s", prefix, s);
140         if (!event->name)
141                 goto error;
142
143         if (of_property_read_string(np, "scale", &s))
144                 s = scale;
145
146         if (s) {
147                 event->scale = kstrdup(s, GFP_KERNEL);
148                 if (!event->scale)
149                         goto error;
150         }
151
152         if (of_property_read_string(np, "unit", &s))
153                 s = unit;
154
155         if (s) {
156                 event->unit = kstrdup(s, GFP_KERNEL);
157                 if (!event->unit)
158                         goto error;
159         }
160
161         return event;
162 error:
163         kfree(event->unit);
164         kfree(event->scale);
165         kfree(event->name);
166         kfree(event);
167
168         return NULL;
169 }
170
171 /*
172  * update_events_in_group: Update the "events" information in an attr_group
173  *                         and assign the attr_group to the pmu "pmu".
174  */
175 static int update_events_in_group(struct device_node *node, struct imc_pmu *pmu)
176 {
177         struct attribute_group *attr_group;
178         struct attribute **attrs, *dev_str;
179         struct device_node *np, *pmu_events;
180         struct imc_events *ev;
181         u32 handle, base_reg;
182         int i=0, j=0, ct;
183         const char *prefix, *g_scale, *g_unit;
184         const char *ev_val_str, *ev_scale_str, *ev_unit_str;
185
186         if (!of_property_read_u32(node, "events", &handle))
187                 pmu_events = of_find_node_by_phandle(handle);
188         else
189                 return 0;
190
191         /* Did not find any node with a given phandle */
192         if (!pmu_events)
193                 return 0;
194
195         /* Get a count of number of child nodes */
196         ct = of_get_child_count(pmu_events);
197
198         /* Get the event prefix */
199         if (of_property_read_string(node, "events-prefix", &prefix))
200                 return 0;
201
202         /* Get a global unit and scale data if available */
203         if (of_property_read_string(node, "scale", &g_scale))
204                 g_scale = NULL;
205
206         if (of_property_read_string(node, "unit", &g_unit))
207                 g_unit = NULL;
208
209         /* "reg" property gives out the base offset of the counters data */
210         of_property_read_u32(node, "reg", &base_reg);
211
212         /* Allocate memory for the events */
213         pmu->events = kcalloc(ct, sizeof(struct imc_events), GFP_KERNEL);
214         if (!pmu->events)
215                 return -ENOMEM;
216
217         ct = 0;
218         /* Parse the events and update the struct */
219         for_each_child_of_node(pmu_events, np) {
220                 ev = imc_parse_event(np, g_scale, g_unit, prefix, base_reg);
221                 if (ev)
222                         pmu->events[ct++] = ev;
223         }
224
225         /* Allocate memory for attribute group */
226         attr_group = kzalloc(sizeof(*attr_group), GFP_KERNEL);
227         if (!attr_group)
228                 return -ENOMEM;
229
230         /*
231          * Allocate memory for attributes.
232          * Since we have count of events for this pmu, we also allocate
233          * memory for the scale and unit attribute for now.
234          * "ct" has the total event structs added from the events-parent node.
235          * So allocate three times the "ct" (this includes event, event_scale and
236          * event_unit).
237          */
238         attrs = kcalloc(((ct * 3) + 1), sizeof(struct attribute *), GFP_KERNEL);
239         if (!attrs) {
240                 kfree(attr_group);
241                 kfree(pmu->events);
242                 return -ENOMEM;
243         }
244
245         attr_group->name = "events";
246         attr_group->attrs = attrs;
247         do {
248                 ev_val_str = kasprintf(GFP_KERNEL, "event=0x%x", pmu->events[i]->value);
249                 dev_str = device_str_attr_create(pmu->events[i]->name, ev_val_str);
250                 if (!dev_str)
251                         continue;
252
253                 attrs[j++] = dev_str;
254                 if (pmu->events[i]->scale) {
255                         ev_scale_str = kasprintf(GFP_KERNEL, "%s.scale",pmu->events[i]->name);
256                         dev_str = device_str_attr_create(ev_scale_str, pmu->events[i]->scale);
257                         if (!dev_str)
258                                 continue;
259
260                         attrs[j++] = dev_str;
261                 }
262
263                 if (pmu->events[i]->unit) {
264                         ev_unit_str = kasprintf(GFP_KERNEL, "%s.unit",pmu->events[i]->name);
265                         dev_str = device_str_attr_create(ev_unit_str, pmu->events[i]->unit);
266                         if (!dev_str)
267                                 continue;
268
269                         attrs[j++] = dev_str;
270                 }
271         } while (++i < ct);
272
273         /* Save the event attribute */
274         pmu->attr_groups[IMC_EVENT_ATTR] = attr_group;
275
276         kfree(pmu->events);
277         return 0;
278 }
279
280 /* get_nest_pmu_ref: Return the imc_pmu_ref struct for the given node */
281 static struct imc_pmu_ref *get_nest_pmu_ref(int cpu)
282 {
283         return per_cpu(local_nest_imc_refc, cpu);
284 }
285
286 static void nest_change_cpu_context(int old_cpu, int new_cpu)
287 {
288         struct imc_pmu **pn = per_nest_pmu_arr;
289         int i;
290
291         if (old_cpu < 0 || new_cpu < 0)
292                 return;
293
294         for (i = 0; *pn && i < IMC_MAX_PMUS; i++, pn++)
295                 perf_pmu_migrate_context(&(*pn)->pmu, old_cpu, new_cpu);
296 }
297
298 static int ppc_nest_imc_cpu_offline(unsigned int cpu)
299 {
300         int nid, target = -1;
301         const struct cpumask *l_cpumask;
302         struct imc_pmu_ref *ref;
303
304         /*
305          * Check in the designated list for this cpu. Dont bother
306          * if not one of them.
307          */
308         if (!cpumask_test_and_clear_cpu(cpu, &nest_imc_cpumask))
309                 return 0;
310
311         /*
312          * Check whether nest_imc is registered. We could end up here if the
313          * cpuhotplug callback registration fails. i.e, callback invokes the
314          * offline path for all successfully registered nodes. At this stage,
315          * nest_imc pmu will not be registered and we should return here.
316          *
317          * We return with a zero since this is not an offline failure. And
318          * cpuhp_setup_state() returns the actual failure reason to the caller,
319          * which in turn will call the cleanup routine.
320          */
321         if (!nest_pmus)
322                 return 0;
323
324         /*
325          * Now that this cpu is one of the designated,
326          * find a next cpu a) which is online and b) in same chip.
327          */
328         nid = cpu_to_node(cpu);
329         l_cpumask = cpumask_of_node(nid);
330         target = cpumask_any_but(l_cpumask, cpu);
331
332         /*
333          * Update the cpumask with the target cpu and
334          * migrate the context if needed
335          */
336         if (target >= 0 && target < nr_cpu_ids) {
337                 cpumask_set_cpu(target, &nest_imc_cpumask);
338                 nest_change_cpu_context(cpu, target);
339         } else {
340                 opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
341                                        get_hard_smp_processor_id(cpu));
342                 /*
343                  * If this is the last cpu in this chip then, skip the reference
344                  * count mutex lock and make the reference count on this chip zero.
345                  */
346                 ref = get_nest_pmu_ref(cpu);
347                 if (!ref)
348                         return -EINVAL;
349
350                 ref->refc = 0;
351         }
352         return 0;
353 }
354
355 static int ppc_nest_imc_cpu_online(unsigned int cpu)
356 {
357         const struct cpumask *l_cpumask;
358         static struct cpumask tmp_mask;
359         int res;
360
361         /* Get the cpumask of this node */
362         l_cpumask = cpumask_of_node(cpu_to_node(cpu));
363
364         /*
365          * If this is not the first online CPU on this node, then
366          * just return.
367          */
368         if (cpumask_and(&tmp_mask, l_cpumask, &nest_imc_cpumask))
369                 return 0;
370
371         /*
372          * If this is the first online cpu on this node
373          * disable the nest counters by making an OPAL call.
374          */
375         res = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
376                                      get_hard_smp_processor_id(cpu));
377         if (res)
378                 return res;
379
380         /* Make this CPU the designated target for counter collection */
381         cpumask_set_cpu(cpu, &nest_imc_cpumask);
382         return 0;
383 }
384
385 static int nest_pmu_cpumask_init(void)
386 {
387         return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE,
388                                  "perf/powerpc/imc:online",
389                                  ppc_nest_imc_cpu_online,
390                                  ppc_nest_imc_cpu_offline);
391 }
392
393 static void nest_imc_counters_release(struct perf_event *event)
394 {
395         int rc, node_id;
396         struct imc_pmu_ref *ref;
397
398         if (event->cpu < 0)
399                 return;
400
401         node_id = cpu_to_node(event->cpu);
402
403         /*
404          * See if we need to disable the nest PMU.
405          * If no events are currently in use, then we have to take a
406          * mutex to ensure that we don't race with another task doing
407          * enable or disable the nest counters.
408          */
409         ref = get_nest_pmu_ref(event->cpu);
410         if (!ref)
411                 return;
412
413         /* Take the mutex lock for this node and then decrement the reference count */
414         mutex_lock(&ref->lock);
415         if (ref->refc == 0) {
416                 /*
417                  * The scenario where this is true is, when perf session is
418                  * started, followed by offlining of all cpus in a given node.
419                  *
420                  * In the cpuhotplug offline path, ppc_nest_imc_cpu_offline()
421                  * function set the ref->count to zero, if the cpu which is
422                  * about to offline is the last cpu in a given node and make
423                  * an OPAL call to disable the engine in that node.
424                  *
425                  */
426                 mutex_unlock(&ref->lock);
427                 return;
428         }
429         ref->refc--;
430         if (ref->refc == 0) {
431                 rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
432                                             get_hard_smp_processor_id(event->cpu));
433                 if (rc) {
434                         mutex_unlock(&ref->lock);
435                         pr_err("nest-imc: Unable to stop the counters for core %d\n", node_id);
436                         return;
437                 }
438         } else if (ref->refc < 0) {
439                 WARN(1, "nest-imc: Invalid event reference count\n");
440                 ref->refc = 0;
441         }
442         mutex_unlock(&ref->lock);
443 }
444
445 static int nest_imc_event_init(struct perf_event *event)
446 {
447         int chip_id, rc, node_id;
448         u32 l_config, config = event->attr.config;
449         struct imc_mem_info *pcni;
450         struct imc_pmu *pmu;
451         struct imc_pmu_ref *ref;
452         bool flag = false;
453
454         if (event->attr.type != event->pmu->type)
455                 return -ENOENT;
456
457         /* Sampling not supported */
458         if (event->hw.sample_period)
459                 return -EINVAL;
460
461         /* unsupported modes and filters */
462         if (event->attr.exclude_user   ||
463             event->attr.exclude_kernel ||
464             event->attr.exclude_hv     ||
465             event->attr.exclude_idle   ||
466             event->attr.exclude_host   ||
467             event->attr.exclude_guest)
468                 return -EINVAL;
469
470         if (event->cpu < 0)
471                 return -EINVAL;
472
473         pmu = imc_event_to_pmu(event);
474
475         /* Sanity check for config (event offset) */
476         if ((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size)
477                 return -EINVAL;
478
479         /*
480          * Nest HW counter memory resides in a per-chip reserve-memory (HOMER).
481          * Get the base memory addresss for this cpu.
482          */
483         chip_id = cpu_to_chip_id(event->cpu);
484         pcni = pmu->mem_info;
485         do {
486                 if (pcni->id == chip_id) {
487                         flag = true;
488                         break;
489                 }
490                 pcni++;
491         } while (pcni);
492
493         if (!flag)
494                 return -ENODEV;
495
496         /*
497          * Add the event offset to the base address.
498          */
499         l_config = config & IMC_EVENT_OFFSET_MASK;
500         event->hw.event_base = (u64)pcni->vbase + l_config;
501         node_id = cpu_to_node(event->cpu);
502
503         /*
504          * Get the imc_pmu_ref struct for this node.
505          * Take the mutex lock and then increment the count of nest pmu events
506          * inited.
507          */
508         ref = get_nest_pmu_ref(event->cpu);
509         if (!ref)
510                 return -EINVAL;
511
512         mutex_lock(&ref->lock);
513         if (ref->refc == 0) {
514                 rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_NEST,
515                                              get_hard_smp_processor_id(event->cpu));
516                 if (rc) {
517                         mutex_unlock(&ref->lock);
518                         pr_err("nest-imc: Unable to start the counters for node %d\n",
519                                                                         node_id);
520                         return rc;
521                 }
522         }
523         ++ref->refc;
524         mutex_unlock(&ref->lock);
525
526         event->destroy = nest_imc_counters_release;
527         return 0;
528 }
529
530 /*
531  * core_imc_mem_init : Initializes memory for the current core.
532  *
533  * Uses alloc_pages_node() and uses the returned address as an argument to
534  * an opal call to configure the pdbar. The address sent as an argument is
535  * converted to physical address before the opal call is made. This is the
536  * base address at which the core imc counters are populated.
537  */
538 static int core_imc_mem_init(int cpu, int size)
539 {
540         int nid, rc = 0, core_id = (cpu / threads_per_core);
541         struct imc_mem_info *mem_info;
542
543         /*
544          * alloc_pages_node() will allocate memory for core in the
545          * local node only.
546          */
547         nid = cpu_to_node(cpu);
548         mem_info = &core_imc_pmu->mem_info[core_id];
549         mem_info->id = core_id;
550
551         /* We need only vbase for core counters */
552         mem_info->vbase = page_address(alloc_pages_node(nid,
553                                           GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
554                                           __GFP_NOWARN, get_order(size)));
555         if (!mem_info->vbase)
556                 return -ENOMEM;
557
558         /* Init the mutex */
559         core_imc_refc[core_id].id = core_id;
560         mutex_init(&core_imc_refc[core_id].lock);
561
562         rc = opal_imc_counters_init(OPAL_IMC_COUNTERS_CORE,
563                                 __pa((void *)mem_info->vbase),
564                                 get_hard_smp_processor_id(cpu));
565         if (rc) {
566                 free_pages((u64)mem_info->vbase, get_order(size));
567                 mem_info->vbase = NULL;
568         }
569
570         return rc;
571 }
572
573 static bool is_core_imc_mem_inited(int cpu)
574 {
575         struct imc_mem_info *mem_info;
576         int core_id = (cpu / threads_per_core);
577
578         mem_info = &core_imc_pmu->mem_info[core_id];
579         if (!mem_info->vbase)
580                 return false;
581
582         return true;
583 }
584
585 static int ppc_core_imc_cpu_online(unsigned int cpu)
586 {
587         const struct cpumask *l_cpumask;
588         static struct cpumask tmp_mask;
589         int ret = 0;
590
591         /* Get the cpumask for this core */
592         l_cpumask = cpu_sibling_mask(cpu);
593
594         /* If a cpu for this core is already set, then, don't do anything */
595         if (cpumask_and(&tmp_mask, l_cpumask, &core_imc_cpumask))
596                 return 0;
597
598         if (!is_core_imc_mem_inited(cpu)) {
599                 ret = core_imc_mem_init(cpu, core_imc_pmu->counter_mem_size);
600                 if (ret) {
601                         pr_info("core_imc memory allocation for cpu %d failed\n", cpu);
602                         return ret;
603                 }
604         }
605
606         /* set the cpu in the mask */
607         cpumask_set_cpu(cpu, &core_imc_cpumask);
608         return 0;
609 }
610
611 static int ppc_core_imc_cpu_offline(unsigned int cpu)
612 {
613         unsigned int ncpu, core_id;
614         struct imc_pmu_ref *ref;
615
616         /*
617          * clear this cpu out of the mask, if not present in the mask,
618          * don't bother doing anything.
619          */
620         if (!cpumask_test_and_clear_cpu(cpu, &core_imc_cpumask))
621                 return 0;
622
623         /*
624          * Check whether core_imc is registered. We could end up here
625          * if the cpuhotplug callback registration fails. i.e, callback
626          * invokes the offline path for all sucessfully registered cpus.
627          * At this stage, core_imc pmu will not be registered and we
628          * should return here.
629          *
630          * We return with a zero since this is not an offline failure.
631          * And cpuhp_setup_state() returns the actual failure reason
632          * to the caller, which inturn will call the cleanup routine.
633          */
634         if (!core_imc_pmu->pmu.event_init)
635                 return 0;
636
637         /* Find any online cpu in that core except the current "cpu" */
638         ncpu = cpumask_any_but(cpu_sibling_mask(cpu), cpu);
639
640         if (ncpu >= 0 && ncpu < nr_cpu_ids) {
641                 cpumask_set_cpu(ncpu, &core_imc_cpumask);
642                 perf_pmu_migrate_context(&core_imc_pmu->pmu, cpu, ncpu);
643         } else {
644                 /*
645                  * If this is the last cpu in this core then, skip taking refernce
646                  * count mutex lock for this core and directly zero "refc" for
647                  * this core.
648                  */
649                 opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
650                                        get_hard_smp_processor_id(cpu));
651                 core_id = cpu / threads_per_core;
652                 ref = &core_imc_refc[core_id];
653                 if (!ref)
654                         return -EINVAL;
655
656                 ref->refc = 0;
657         }
658         return 0;
659 }
660
661 static int core_imc_pmu_cpumask_init(void)
662 {
663         return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE,
664                                  "perf/powerpc/imc_core:online",
665                                  ppc_core_imc_cpu_online,
666                                  ppc_core_imc_cpu_offline);
667 }
668
669 static void core_imc_counters_release(struct perf_event *event)
670 {
671         int rc, core_id;
672         struct imc_pmu_ref *ref;
673
674         if (event->cpu < 0)
675                 return;
676         /*
677          * See if we need to disable the IMC PMU.
678          * If no events are currently in use, then we have to take a
679          * mutex to ensure that we don't race with another task doing
680          * enable or disable the core counters.
681          */
682         core_id = event->cpu / threads_per_core;
683
684         /* Take the mutex lock and decrement the refernce count for this core */
685         ref = &core_imc_refc[core_id];
686         if (!ref)
687                 return;
688
689         mutex_lock(&ref->lock);
690         if (ref->refc == 0) {
691                 /*
692                  * The scenario where this is true is, when perf session is
693                  * started, followed by offlining of all cpus in a given core.
694                  *
695                  * In the cpuhotplug offline path, ppc_core_imc_cpu_offline()
696                  * function set the ref->count to zero, if the cpu which is
697                  * about to offline is the last cpu in a given core and make
698                  * an OPAL call to disable the engine in that core.
699                  *
700                  */
701                 mutex_unlock(&ref->lock);
702                 return;
703         }
704         ref->refc--;
705         if (ref->refc == 0) {
706                 rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
707                                             get_hard_smp_processor_id(event->cpu));
708                 if (rc) {
709                         mutex_unlock(&ref->lock);
710                         pr_err("IMC: Unable to stop the counters for core %d\n", core_id);
711                         return;
712                 }
713         } else if (ref->refc < 0) {
714                 WARN(1, "core-imc: Invalid event reference count\n");
715                 ref->refc = 0;
716         }
717         mutex_unlock(&ref->lock);
718 }
719
720 static int core_imc_event_init(struct perf_event *event)
721 {
722         int core_id, rc;
723         u64 config = event->attr.config;
724         struct imc_mem_info *pcmi;
725         struct imc_pmu *pmu;
726         struct imc_pmu_ref *ref;
727
728         if (event->attr.type != event->pmu->type)
729                 return -ENOENT;
730
731         /* Sampling not supported */
732         if (event->hw.sample_period)
733                 return -EINVAL;
734
735         /* unsupported modes and filters */
736         if (event->attr.exclude_user   ||
737             event->attr.exclude_kernel ||
738             event->attr.exclude_hv     ||
739             event->attr.exclude_idle   ||
740             event->attr.exclude_host   ||
741             event->attr.exclude_guest)
742                 return -EINVAL;
743
744         if (event->cpu < 0)
745                 return -EINVAL;
746
747         event->hw.idx = -1;
748         pmu = imc_event_to_pmu(event);
749
750         /* Sanity check for config (event offset) */
751         if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
752                 return -EINVAL;
753
754         if (!is_core_imc_mem_inited(event->cpu))
755                 return -ENODEV;
756
757         core_id = event->cpu / threads_per_core;
758         pcmi = &core_imc_pmu->mem_info[core_id];
759         if ((!pcmi->vbase))
760                 return -ENODEV;
761
762         /* Get the core_imc mutex for this core */
763         ref = &core_imc_refc[core_id];
764         if (!ref)
765                 return -EINVAL;
766
767         /*
768          * Core pmu units are enabled only when it is used.
769          * See if this is triggered for the first time.
770          * If yes, take the mutex lock and enable the core counters.
771          * If not, just increment the count in core_imc_refc struct.
772          */
773         mutex_lock(&ref->lock);
774         if (ref->refc == 0) {
775                 rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
776                                              get_hard_smp_processor_id(event->cpu));
777                 if (rc) {
778                         mutex_unlock(&ref->lock);
779                         pr_err("core-imc: Unable to start the counters for core %d\n",
780                                                                         core_id);
781                         return rc;
782                 }
783         }
784         ++ref->refc;
785         mutex_unlock(&ref->lock);
786
787         event->hw.event_base = (u64)pcmi->vbase + (config & IMC_EVENT_OFFSET_MASK);
788         event->destroy = core_imc_counters_release;
789         return 0;
790 }
791
792 /*
793  * Allocates a page of memory for each of the online cpus, and write the
794  * physical base address of that page to the LDBAR for that cpu.
795  *
796  * LDBAR Register Layout:
797  *
798  *  0          4         8         12        16        20        24        28
799  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
800  *   | |       [   ]    [                   Counter Address [8:50]
801  *   | * Mode    |
802  *   |           * PB Scope
803  *   * Enable/Disable
804  *
805  *  32        36        40        44        48        52        56        60
806  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
807  *           Counter Address [8:50]              ]
808  *
809  */
810 static int thread_imc_mem_alloc(int cpu_id, int size)
811 {
812         u64 ldbar_value, *local_mem = per_cpu(thread_imc_mem, cpu_id);
813         int nid = cpu_to_node(cpu_id);
814
815         if (!local_mem) {
816                 /*
817                  * This case could happen only once at start, since we dont
818                  * free the memory in cpu offline path.
819                  */
820                 local_mem = page_address(alloc_pages_node(nid,
821                                   GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
822                                   __GFP_NOWARN, get_order(size)));
823                 if (!local_mem)
824                         return -ENOMEM;
825
826                 per_cpu(thread_imc_mem, cpu_id) = local_mem;
827         }
828
829         ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | THREAD_IMC_ENABLE;
830
831         mtspr(SPRN_LDBAR, ldbar_value);
832         return 0;
833 }
834
835 static int ppc_thread_imc_cpu_online(unsigned int cpu)
836 {
837         return thread_imc_mem_alloc(cpu, thread_imc_mem_size);
838 }
839
840 static int ppc_thread_imc_cpu_offline(unsigned int cpu)
841 {
842         mtspr(SPRN_LDBAR, 0);
843         return 0;
844 }
845
846 static int thread_imc_cpu_init(void)
847 {
848         return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE,
849                           "perf/powerpc/imc_thread:online",
850                           ppc_thread_imc_cpu_online,
851                           ppc_thread_imc_cpu_offline);
852 }
853
854 void thread_imc_pmu_sched_task(struct perf_event_context *ctx,
855                                       bool sched_in)
856 {
857         int core_id;
858         struct imc_pmu_ref *ref;
859
860         if (!is_core_imc_mem_inited(smp_processor_id()))
861                 return;
862
863         core_id = smp_processor_id() / threads_per_core;
864         /*
865          * imc pmus are enabled only when it is used.
866          * See if this is triggered for the first time.
867          * If yes, take the mutex lock and enable the counters.
868          * If not, just increment the count in ref count struct.
869          */
870         ref = &core_imc_refc[core_id];
871         if (!ref)
872                 return;
873
874         if (sched_in) {
875                 mutex_lock(&ref->lock);
876                 if (ref->refc == 0) {
877                         if (opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
878                              get_hard_smp_processor_id(smp_processor_id()))) {
879                                 mutex_unlock(&ref->lock);
880                                 pr_err("thread-imc: Unable to start the counter\
881                                                         for core %d\n", core_id);
882                                 return;
883                         }
884                 }
885                 ++ref->refc;
886                 mutex_unlock(&ref->lock);
887         } else {
888                 mutex_lock(&ref->lock);
889                 ref->refc--;
890                 if (ref->refc == 0) {
891                         if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
892                             get_hard_smp_processor_id(smp_processor_id()))) {
893                                 mutex_unlock(&ref->lock);
894                                 pr_err("thread-imc: Unable to stop the counters\
895                                                         for core %d\n", core_id);
896                                 return;
897                         }
898                 } else if (ref->refc < 0) {
899                         ref->refc = 0;
900                 }
901                 mutex_unlock(&ref->lock);
902         }
903
904         return;
905 }
906
907 static int thread_imc_event_init(struct perf_event *event)
908 {
909         u32 config = event->attr.config;
910         struct task_struct *target;
911         struct imc_pmu *pmu;
912
913         if (event->attr.type != event->pmu->type)
914                 return -ENOENT;
915
916         /* Sampling not supported */
917         if (event->hw.sample_period)
918                 return -EINVAL;
919
920         event->hw.idx = -1;
921         pmu = imc_event_to_pmu(event);
922
923         /* Sanity check for config offset */
924         if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
925                 return -EINVAL;
926
927         target = event->hw.target;
928         if (!target)
929                 return -EINVAL;
930
931         event->pmu->task_ctx_nr = perf_sw_context;
932         return 0;
933 }
934
935 static bool is_thread_imc_pmu(struct perf_event *event)
936 {
937         if (!strncmp(event->pmu->name, "thread_imc", strlen("thread_imc")))
938                 return true;
939
940         return false;
941 }
942
943 static u64 * get_event_base_addr(struct perf_event *event)
944 {
945         u64 addr;
946
947         if (is_thread_imc_pmu(event)) {
948                 addr = (u64)per_cpu(thread_imc_mem, smp_processor_id());
949                 return (u64 *)(addr + (event->attr.config & IMC_EVENT_OFFSET_MASK));
950         }
951
952         return (u64 *)event->hw.event_base;
953 }
954
955 static void thread_imc_pmu_start_txn(struct pmu *pmu,
956                                      unsigned int txn_flags)
957 {
958         if (txn_flags & ~PERF_PMU_TXN_ADD)
959                 return;
960         perf_pmu_disable(pmu);
961 }
962
963 static void thread_imc_pmu_cancel_txn(struct pmu *pmu)
964 {
965         perf_pmu_enable(pmu);
966 }
967
968 static int thread_imc_pmu_commit_txn(struct pmu *pmu)
969 {
970         perf_pmu_enable(pmu);
971         return 0;
972 }
973
974 static u64 imc_read_counter(struct perf_event *event)
975 {
976         u64 *addr, data;
977
978         /*
979          * In-Memory Collection (IMC) counters are free flowing counters.
980          * So we take a snapshot of the counter value on enable and save it
981          * to calculate the delta at later stage to present the event counter
982          * value.
983          */
984         addr = get_event_base_addr(event);
985         data = be64_to_cpu(READ_ONCE(*addr));
986         local64_set(&event->hw.prev_count, data);
987
988         return data;
989 }
990
991 static void imc_event_update(struct perf_event *event)
992 {
993         u64 counter_prev, counter_new, final_count;
994
995         counter_prev = local64_read(&event->hw.prev_count);
996         counter_new = imc_read_counter(event);
997         final_count = counter_new - counter_prev;
998
999         /* Update the delta to the event count */
1000         local64_add(final_count, &event->count);
1001 }
1002
1003 static void imc_event_start(struct perf_event *event, int flags)
1004 {
1005         /*
1006          * In Memory Counters are free flowing counters. HW or the microcode
1007          * keeps adding to the counter offset in memory. To get event
1008          * counter value, we snapshot the value here and we calculate
1009          * delta at later point.
1010          */
1011         imc_read_counter(event);
1012 }
1013
1014 static void imc_event_stop(struct perf_event *event, int flags)
1015 {
1016         /*
1017          * Take a snapshot and calculate the delta and update
1018          * the event counter values.
1019          */
1020         imc_event_update(event);
1021 }
1022
1023 static int imc_event_add(struct perf_event *event, int flags)
1024 {
1025         if (flags & PERF_EF_START)
1026                 imc_event_start(event, flags);
1027
1028         return 0;
1029 }
1030
1031 static int thread_imc_event_add(struct perf_event *event, int flags)
1032 {
1033         if (flags & PERF_EF_START)
1034                 imc_event_start(event, flags);
1035
1036         /* Enable the sched_task to start the engine */
1037         perf_sched_cb_inc(event->ctx->pmu);
1038         return 0;
1039 }
1040
1041 static void thread_imc_event_del(struct perf_event *event, int flags)
1042 {
1043         /*
1044          * Take a snapshot and calculate the delta and update
1045          * the event counter values.
1046          */
1047         imc_event_update(event);
1048         perf_sched_cb_dec(event->ctx->pmu);
1049 }
1050
1051 /* update_pmu_ops : Populate the appropriate operations for "pmu" */
1052 static int update_pmu_ops(struct imc_pmu *pmu)
1053 {
1054         pmu->pmu.task_ctx_nr = perf_invalid_context;
1055         pmu->pmu.add = imc_event_add;
1056         pmu->pmu.del = imc_event_stop;
1057         pmu->pmu.start = imc_event_start;
1058         pmu->pmu.stop = imc_event_stop;
1059         pmu->pmu.read = imc_event_update;
1060         pmu->pmu.attr_groups = pmu->attr_groups;
1061         pmu->attr_groups[IMC_FORMAT_ATTR] = &imc_format_group;
1062
1063         switch (pmu->domain) {
1064         case IMC_DOMAIN_NEST:
1065                 pmu->pmu.event_init = nest_imc_event_init;
1066                 pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1067                 break;
1068         case IMC_DOMAIN_CORE:
1069                 pmu->pmu.event_init = core_imc_event_init;
1070                 pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1071                 break;
1072         case IMC_DOMAIN_THREAD:
1073                 pmu->pmu.event_init = thread_imc_event_init;
1074                 pmu->pmu.sched_task = thread_imc_pmu_sched_task;
1075                 pmu->pmu.add = thread_imc_event_add;
1076                 pmu->pmu.del = thread_imc_event_del;
1077                 pmu->pmu.start_txn = thread_imc_pmu_start_txn;
1078                 pmu->pmu.cancel_txn = thread_imc_pmu_cancel_txn;
1079                 pmu->pmu.commit_txn = thread_imc_pmu_commit_txn;
1080                 break;
1081         default:
1082                 break;
1083         }
1084
1085         return 0;
1086 }
1087
1088 /* init_nest_pmu_ref: Initialize the imc_pmu_ref struct for all the nodes */
1089 static int init_nest_pmu_ref(void)
1090 {
1091         int nid, i, cpu;
1092
1093         nest_imc_refc = kcalloc(num_possible_nodes(), sizeof(*nest_imc_refc),
1094                                                                 GFP_KERNEL);
1095
1096         if (!nest_imc_refc)
1097                 return -ENOMEM;
1098
1099         i = 0;
1100         for_each_node(nid) {
1101                 /*
1102                  * Mutex lock to avoid races while tracking the number of
1103                  * sessions using the chip's nest pmu units.
1104                  */
1105                 mutex_init(&nest_imc_refc[i].lock);
1106
1107                 /*
1108                  * Loop to init the "id" with the node_id. Variable "i" initialized to
1109                  * 0 and will be used as index to the array. "i" will not go off the
1110                  * end of the array since the "for_each_node" loops for "N_POSSIBLE"
1111                  * nodes only.
1112                  */
1113                 nest_imc_refc[i++].id = nid;
1114         }
1115
1116         /*
1117          * Loop to init the per_cpu "local_nest_imc_refc" with the proper
1118          * "nest_imc_refc" index. This makes get_nest_pmu_ref() alot simple.
1119          */
1120         for_each_possible_cpu(cpu) {
1121                 nid = cpu_to_node(cpu);
1122                 for (i = 0; i < num_possible_nodes(); i++) {
1123                         if (nest_imc_refc[i].id == nid) {
1124                                 per_cpu(local_nest_imc_refc, cpu) = &nest_imc_refc[i];
1125                                 break;
1126                         }
1127                 }
1128         }
1129         return 0;
1130 }
1131
1132 static void cleanup_all_core_imc_memory(void)
1133 {
1134         int i, nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1135         struct imc_mem_info *ptr = core_imc_pmu->mem_info;
1136         int size = core_imc_pmu->counter_mem_size;
1137
1138         /* mem_info will never be NULL */
1139         for (i = 0; i < nr_cores; i++) {
1140                 if (ptr[i].vbase)
1141                         free_pages((u64)ptr->vbase, get_order(size));
1142         }
1143
1144         kfree(ptr);
1145         kfree(core_imc_refc);
1146 }
1147
1148 static void thread_imc_ldbar_disable(void *dummy)
1149 {
1150         /*
1151          * By Zeroing LDBAR, we disable thread-imc
1152          * updates.
1153          */
1154         mtspr(SPRN_LDBAR, 0);
1155 }
1156
1157 void thread_imc_disable(void)
1158 {
1159         on_each_cpu(thread_imc_ldbar_disable, NULL, 1);
1160 }
1161
1162 static void cleanup_all_thread_imc_memory(void)
1163 {
1164         int i, order = get_order(thread_imc_mem_size);
1165
1166         for_each_online_cpu(i) {
1167                 if (per_cpu(thread_imc_mem, i))
1168                         free_pages((u64)per_cpu(thread_imc_mem, i), order);
1169
1170         }
1171 }
1172
1173 /*
1174  * Common function to unregister cpu hotplug callback and
1175  * free the memory.
1176  * TODO: Need to handle pmu unregistering, which will be
1177  * done in followup series.
1178  */
1179 static void imc_common_cpuhp_mem_free(struct imc_pmu *pmu_ptr)
1180 {
1181         if (pmu_ptr->domain == IMC_DOMAIN_NEST) {
1182                 mutex_lock(&nest_init_lock);
1183                 if (nest_pmus == 1) {
1184                         cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE);
1185                         kfree(nest_imc_refc);
1186                 }
1187
1188                 if (nest_pmus > 0)
1189                         nest_pmus--;
1190                 mutex_unlock(&nest_init_lock);
1191         }
1192
1193         /* Free core_imc memory */
1194         if (pmu_ptr->domain == IMC_DOMAIN_CORE) {
1195                 cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE);
1196                 cleanup_all_core_imc_memory();
1197         }
1198
1199         /* Free thread_imc memory */
1200         if (pmu_ptr->domain == IMC_DOMAIN_THREAD) {
1201                 cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE);
1202                 cleanup_all_thread_imc_memory();
1203         }
1204
1205         /* Only free the attr_groups which are dynamically allocated  */
1206         if (pmu_ptr->attr_groups[IMC_EVENT_ATTR])
1207                 kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]->attrs);
1208         kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]);
1209         kfree(pmu_ptr);
1210         return;
1211 }
1212
1213
1214 /*
1215  * imc_mem_init : Function to support memory allocation for core imc.
1216  */
1217 static int imc_mem_init(struct imc_pmu *pmu_ptr, struct device_node *parent,
1218                                                                 int pmu_index)
1219 {
1220         const char *s;
1221         int nr_cores, cpu, res;
1222
1223         if (of_property_read_string(parent, "name", &s))
1224                 return -ENODEV;
1225
1226         switch (pmu_ptr->domain) {
1227         case IMC_DOMAIN_NEST:
1228                 /* Update the pmu name */
1229                 pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s_imc", "nest_", s);
1230                 if (!pmu_ptr->pmu.name)
1231                         return -ENOMEM;
1232
1233                 /* Needed for hotplug/migration */
1234                 per_nest_pmu_arr[pmu_index] = pmu_ptr;
1235                 break;
1236         case IMC_DOMAIN_CORE:
1237                 /* Update the pmu name */
1238                 pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1239                 if (!pmu_ptr->pmu.name)
1240                         return -ENOMEM;
1241
1242                 nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1243                 pmu_ptr->mem_info = kcalloc(nr_cores, sizeof(struct imc_mem_info),
1244                                                                 GFP_KERNEL);
1245
1246                 if (!pmu_ptr->mem_info)
1247                         return -ENOMEM;
1248
1249                 core_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1250                                                                 GFP_KERNEL);
1251
1252                 if (!core_imc_refc)
1253                         return -ENOMEM;
1254
1255                 core_imc_pmu = pmu_ptr;
1256                 break;
1257         case IMC_DOMAIN_THREAD:
1258                 /* Update the pmu name */
1259                 pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1260                 if (!pmu_ptr->pmu.name)
1261                         return -ENOMEM;
1262
1263                 thread_imc_mem_size = pmu_ptr->counter_mem_size;
1264                 for_each_online_cpu(cpu) {
1265                         res = thread_imc_mem_alloc(cpu, pmu_ptr->counter_mem_size);
1266                         if (res)
1267                                 return res;
1268                 }
1269
1270                 thread_imc_pmu = pmu_ptr;
1271                 break;
1272         default:
1273                 return -EINVAL;
1274         }
1275
1276         return 0;
1277 }
1278
1279 /*
1280  * init_imc_pmu : Setup and register the IMC pmu device.
1281  *
1282  * @parent:     Device tree unit node
1283  * @pmu_ptr:    memory allocated for this pmu
1284  * @pmu_idx:    Count of nest pmc registered
1285  *
1286  * init_imc_pmu() setup pmu cpumask and registers for a cpu hotplug callback.
1287  * Handles failure cases and accordingly frees memory.
1288  */
1289 int init_imc_pmu(struct device_node *parent, struct imc_pmu *pmu_ptr, int pmu_idx)
1290 {
1291         int ret;
1292
1293         ret = imc_mem_init(pmu_ptr, parent, pmu_idx);
1294         if (ret)
1295                 goto err_free;
1296
1297         switch (pmu_ptr->domain) {
1298         case IMC_DOMAIN_NEST:
1299                 /*
1300                 * Nest imc pmu need only one cpu per chip, we initialize the
1301                 * cpumask for the first nest imc pmu and use the same for the
1302                 * rest. To handle the cpuhotplug callback unregister, we track
1303                 * the number of nest pmus in "nest_pmus".
1304                 */
1305                 mutex_lock(&nest_init_lock);
1306                 if (nest_pmus == 0) {
1307                         ret = init_nest_pmu_ref();
1308                         if (ret) {
1309                                 mutex_unlock(&nest_init_lock);
1310                                 goto err_free;
1311                         }
1312                         /* Register for cpu hotplug notification. */
1313                         ret = nest_pmu_cpumask_init();
1314                         if (ret) {
1315                                 mutex_unlock(&nest_init_lock);
1316                                 goto err_free;
1317                         }
1318                 }
1319                 nest_pmus++;
1320                 mutex_unlock(&nest_init_lock);
1321                 break;
1322         case IMC_DOMAIN_CORE:
1323                 ret = core_imc_pmu_cpumask_init();
1324                 if (ret) {
1325                         cleanup_all_core_imc_memory();
1326                         return ret;
1327                 }
1328
1329                 break;
1330         case IMC_DOMAIN_THREAD:
1331                 ret = thread_imc_cpu_init();
1332                 if (ret) {
1333                         cleanup_all_thread_imc_memory();
1334                         return ret;
1335                 }
1336
1337                 break;
1338         default:
1339                 return  -1;     /* Unknown domain */
1340         }
1341
1342         ret = update_events_in_group(parent, pmu_ptr);
1343         if (ret)
1344                 goto err_free;
1345
1346         ret = update_pmu_ops(pmu_ptr);
1347         if (ret)
1348                 goto err_free;
1349
1350         ret = perf_pmu_register(&pmu_ptr->pmu, pmu_ptr->pmu.name, -1);
1351         if (ret)
1352                 goto err_free;
1353
1354         pr_info("%s performance monitor hardware support registered\n",
1355                                                         pmu_ptr->pmu.name);
1356
1357         return 0;
1358
1359 err_free:
1360         imc_common_cpuhp_mem_free(pmu_ptr);
1361         return ret;
1362 }