GNU Linux-libre 4.14.251-gnu1
[releases.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;
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
290         if (old_cpu < 0 || new_cpu < 0)
291                 return;
292
293         while (*pn) {
294                 perf_pmu_migrate_context(&(*pn)->pmu, old_cpu, new_cpu);
295                 pn++;
296         }
297 }
298
299 static int ppc_nest_imc_cpu_offline(unsigned int cpu)
300 {
301         int nid, target = -1;
302         const struct cpumask *l_cpumask;
303         struct imc_pmu_ref *ref;
304
305         /*
306          * Check in the designated list for this cpu. Dont bother
307          * if not one of them.
308          */
309         if (!cpumask_test_and_clear_cpu(cpu, &nest_imc_cpumask))
310                 return 0;
311
312         /*
313          * Check whether nest_imc is registered. We could end up here if the
314          * cpuhotplug callback registration fails. i.e, callback invokes the
315          * offline path for all successfully registered nodes. At this stage,
316          * nest_imc pmu will not be registered and we should return here.
317          *
318          * We return with a zero since this is not an offline failure. And
319          * cpuhp_setup_state() returns the actual failure reason to the caller,
320          * which in turn will call the cleanup routine.
321          */
322         if (!nest_pmus)
323                 return 0;
324
325         /*
326          * Now that this cpu is one of the designated,
327          * find a next cpu a) which is online and b) in same chip.
328          */
329         nid = cpu_to_node(cpu);
330         l_cpumask = cpumask_of_node(nid);
331         target = cpumask_any_but(l_cpumask, cpu);
332
333         /*
334          * Update the cpumask with the target cpu and
335          * migrate the context if needed
336          */
337         if (target >= 0 && target < nr_cpu_ids) {
338                 cpumask_set_cpu(target, &nest_imc_cpumask);
339                 nest_change_cpu_context(cpu, target);
340         } else {
341                 opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
342                                        get_hard_smp_processor_id(cpu));
343                 /*
344                  * If this is the last cpu in this chip then, skip the reference
345                  * count mutex lock and make the reference count on this chip zero.
346                  */
347                 ref = get_nest_pmu_ref(cpu);
348                 if (!ref)
349                         return -EINVAL;
350
351                 ref->refc = 0;
352         }
353         return 0;
354 }
355
356 static int ppc_nest_imc_cpu_online(unsigned int cpu)
357 {
358         const struct cpumask *l_cpumask;
359         static struct cpumask tmp_mask;
360         int res;
361
362         /* Get the cpumask of this node */
363         l_cpumask = cpumask_of_node(cpu_to_node(cpu));
364
365         /*
366          * If this is not the first online CPU on this node, then
367          * just return.
368          */
369         if (cpumask_and(&tmp_mask, l_cpumask, &nest_imc_cpumask))
370                 return 0;
371
372         /*
373          * If this is the first online cpu on this node
374          * disable the nest counters by making an OPAL call.
375          */
376         res = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
377                                      get_hard_smp_processor_id(cpu));
378         if (res)
379                 return res;
380
381         /* Make this CPU the designated target for counter collection */
382         cpumask_set_cpu(cpu, &nest_imc_cpumask);
383         return 0;
384 }
385
386 static int nest_pmu_cpumask_init(void)
387 {
388         return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE,
389                                  "perf/powerpc/imc:online",
390                                  ppc_nest_imc_cpu_online,
391                                  ppc_nest_imc_cpu_offline);
392 }
393
394 static void nest_imc_counters_release(struct perf_event *event)
395 {
396         int rc, node_id;
397         struct imc_pmu_ref *ref;
398
399         if (event->cpu < 0)
400                 return;
401
402         node_id = cpu_to_node(event->cpu);
403
404         /*
405          * See if we need to disable the nest PMU.
406          * If no events are currently in use, then we have to take a
407          * mutex to ensure that we don't race with another task doing
408          * enable or disable the nest counters.
409          */
410         ref = get_nest_pmu_ref(event->cpu);
411         if (!ref)
412                 return;
413
414         /* Take the mutex lock for this node and then decrement the reference count */
415         mutex_lock(&ref->lock);
416         if (ref->refc == 0) {
417                 /*
418                  * The scenario where this is true is, when perf session is
419                  * started, followed by offlining of all cpus in a given node.
420                  *
421                  * In the cpuhotplug offline path, ppc_nest_imc_cpu_offline()
422                  * function set the ref->count to zero, if the cpu which is
423                  * about to offline is the last cpu in a given node and make
424                  * an OPAL call to disable the engine in that node.
425                  *
426                  */
427                 mutex_unlock(&ref->lock);
428                 return;
429         }
430         ref->refc--;
431         if (ref->refc == 0) {
432                 rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
433                                             get_hard_smp_processor_id(event->cpu));
434                 if (rc) {
435                         mutex_unlock(&ref->lock);
436                         pr_err("nest-imc: Unable to stop the counters for core %d\n", node_id);
437                         return;
438                 }
439         } else if (ref->refc < 0) {
440                 WARN(1, "nest-imc: Invalid event reference count\n");
441                 ref->refc = 0;
442         }
443         mutex_unlock(&ref->lock);
444 }
445
446 static int nest_imc_event_init(struct perf_event *event)
447 {
448         int chip_id, rc, node_id;
449         u32 l_config, config = event->attr.config;
450         struct imc_mem_info *pcni;
451         struct imc_pmu *pmu;
452         struct imc_pmu_ref *ref;
453         bool flag = false;
454
455         if (event->attr.type != event->pmu->type)
456                 return -ENOENT;
457
458         /* Sampling not supported */
459         if (event->hw.sample_period)
460                 return -EINVAL;
461
462         /* unsupported modes and filters */
463         if (event->attr.exclude_user   ||
464             event->attr.exclude_kernel ||
465             event->attr.exclude_hv     ||
466             event->attr.exclude_idle   ||
467             event->attr.exclude_host   ||
468             event->attr.exclude_guest)
469                 return -EINVAL;
470
471         if (event->cpu < 0)
472                 return -EINVAL;
473
474         pmu = imc_event_to_pmu(event);
475
476         /* Sanity check for config (event offset) */
477         if ((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size)
478                 return -EINVAL;
479
480         /*
481          * Nest HW counter memory resides in a per-chip reserve-memory (HOMER).
482          * Get the base memory addresss for this cpu.
483          */
484         chip_id = cpu_to_chip_id(event->cpu);
485
486         /* Return, if chip_id is not valid */
487         if (chip_id < 0)
488                 return -ENODEV;
489
490         pcni = pmu->mem_info;
491         do {
492                 if (pcni->id == chip_id) {
493                         flag = true;
494                         break;
495                 }
496                 pcni++;
497         } while (pcni);
498
499         if (!flag)
500                 return -ENODEV;
501
502         /*
503          * Add the event offset to the base address.
504          */
505         l_config = config & IMC_EVENT_OFFSET_MASK;
506         event->hw.event_base = (u64)pcni->vbase + l_config;
507         node_id = cpu_to_node(event->cpu);
508
509         /*
510          * Get the imc_pmu_ref struct for this node.
511          * Take the mutex lock and then increment the count of nest pmu events
512          * inited.
513          */
514         ref = get_nest_pmu_ref(event->cpu);
515         if (!ref)
516                 return -EINVAL;
517
518         mutex_lock(&ref->lock);
519         if (ref->refc == 0) {
520                 rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_NEST,
521                                              get_hard_smp_processor_id(event->cpu));
522                 if (rc) {
523                         mutex_unlock(&ref->lock);
524                         pr_err("nest-imc: Unable to start the counters for node %d\n",
525                                                                         node_id);
526                         return rc;
527                 }
528         }
529         ++ref->refc;
530         mutex_unlock(&ref->lock);
531
532         event->destroy = nest_imc_counters_release;
533         return 0;
534 }
535
536 /*
537  * core_imc_mem_init : Initializes memory for the current core.
538  *
539  * Uses alloc_pages_node() and uses the returned address as an argument to
540  * an opal call to configure the pdbar. The address sent as an argument is
541  * converted to physical address before the opal call is made. This is the
542  * base address at which the core imc counters are populated.
543  */
544 static int core_imc_mem_init(int cpu, int size)
545 {
546         int nid, rc = 0, core_id = (cpu / threads_per_core);
547         struct imc_mem_info *mem_info;
548
549         /*
550          * alloc_pages_node() will allocate memory for core in the
551          * local node only.
552          */
553         nid = cpu_to_node(cpu);
554         mem_info = &core_imc_pmu->mem_info[core_id];
555         mem_info->id = core_id;
556
557         /* We need only vbase for core counters */
558         mem_info->vbase = page_address(alloc_pages_node(nid,
559                                           GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
560                                           __GFP_NOWARN, get_order(size)));
561         if (!mem_info->vbase)
562                 return -ENOMEM;
563
564         /* Init the mutex */
565         core_imc_refc[core_id].id = core_id;
566         mutex_init(&core_imc_refc[core_id].lock);
567
568         rc = opal_imc_counters_init(OPAL_IMC_COUNTERS_CORE,
569                                 __pa((void *)mem_info->vbase),
570                                 get_hard_smp_processor_id(cpu));
571         if (rc) {
572                 free_pages((u64)mem_info->vbase, get_order(size));
573                 mem_info->vbase = NULL;
574         }
575
576         return rc;
577 }
578
579 static bool is_core_imc_mem_inited(int cpu)
580 {
581         struct imc_mem_info *mem_info;
582         int core_id = (cpu / threads_per_core);
583
584         mem_info = &core_imc_pmu->mem_info[core_id];
585         if (!mem_info->vbase)
586                 return false;
587
588         return true;
589 }
590
591 static int ppc_core_imc_cpu_online(unsigned int cpu)
592 {
593         const struct cpumask *l_cpumask;
594         static struct cpumask tmp_mask;
595         int ret = 0;
596
597         /* Get the cpumask for this core */
598         l_cpumask = cpu_sibling_mask(cpu);
599
600         /* If a cpu for this core is already set, then, don't do anything */
601         if (cpumask_and(&tmp_mask, l_cpumask, &core_imc_cpumask))
602                 return 0;
603
604         if (!is_core_imc_mem_inited(cpu)) {
605                 ret = core_imc_mem_init(cpu, core_imc_pmu->counter_mem_size);
606                 if (ret) {
607                         pr_info("core_imc memory allocation for cpu %d failed\n", cpu);
608                         return ret;
609                 }
610         }
611
612         /* set the cpu in the mask */
613         cpumask_set_cpu(cpu, &core_imc_cpumask);
614         return 0;
615 }
616
617 static int ppc_core_imc_cpu_offline(unsigned int cpu)
618 {
619         unsigned int ncpu, core_id;
620         struct imc_pmu_ref *ref;
621
622         /*
623          * clear this cpu out of the mask, if not present in the mask,
624          * don't bother doing anything.
625          */
626         if (!cpumask_test_and_clear_cpu(cpu, &core_imc_cpumask))
627                 return 0;
628
629         /*
630          * Check whether core_imc is registered. We could end up here
631          * if the cpuhotplug callback registration fails. i.e, callback
632          * invokes the offline path for all sucessfully registered cpus.
633          * At this stage, core_imc pmu will not be registered and we
634          * should return here.
635          *
636          * We return with a zero since this is not an offline failure.
637          * And cpuhp_setup_state() returns the actual failure reason
638          * to the caller, which inturn will call the cleanup routine.
639          */
640         if (!core_imc_pmu->pmu.event_init)
641                 return 0;
642
643         /* Find any online cpu in that core except the current "cpu" */
644         ncpu = cpumask_any_but(cpu_sibling_mask(cpu), cpu);
645
646         if (ncpu >= 0 && ncpu < nr_cpu_ids) {
647                 cpumask_set_cpu(ncpu, &core_imc_cpumask);
648                 perf_pmu_migrate_context(&core_imc_pmu->pmu, cpu, ncpu);
649         } else {
650                 /*
651                  * If this is the last cpu in this core then, skip taking refernce
652                  * count mutex lock for this core and directly zero "refc" for
653                  * this core.
654                  */
655                 opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
656                                        get_hard_smp_processor_id(cpu));
657                 core_id = cpu / threads_per_core;
658                 ref = &core_imc_refc[core_id];
659                 if (!ref)
660                         return -EINVAL;
661
662                 ref->refc = 0;
663         }
664         return 0;
665 }
666
667 static int core_imc_pmu_cpumask_init(void)
668 {
669         return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE,
670                                  "perf/powerpc/imc_core:online",
671                                  ppc_core_imc_cpu_online,
672                                  ppc_core_imc_cpu_offline);
673 }
674
675 static void core_imc_counters_release(struct perf_event *event)
676 {
677         int rc, core_id;
678         struct imc_pmu_ref *ref;
679
680         if (event->cpu < 0)
681                 return;
682         /*
683          * See if we need to disable the IMC PMU.
684          * If no events are currently in use, then we have to take a
685          * mutex to ensure that we don't race with another task doing
686          * enable or disable the core counters.
687          */
688         core_id = event->cpu / threads_per_core;
689
690         /* Take the mutex lock and decrement the refernce count for this core */
691         ref = &core_imc_refc[core_id];
692         if (!ref)
693                 return;
694
695         mutex_lock(&ref->lock);
696         if (ref->refc == 0) {
697                 /*
698                  * The scenario where this is true is, when perf session is
699                  * started, followed by offlining of all cpus in a given core.
700                  *
701                  * In the cpuhotplug offline path, ppc_core_imc_cpu_offline()
702                  * function set the ref->count to zero, if the cpu which is
703                  * about to offline is the last cpu in a given core and make
704                  * an OPAL call to disable the engine in that core.
705                  *
706                  */
707                 mutex_unlock(&ref->lock);
708                 return;
709         }
710         ref->refc--;
711         if (ref->refc == 0) {
712                 rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
713                                             get_hard_smp_processor_id(event->cpu));
714                 if (rc) {
715                         mutex_unlock(&ref->lock);
716                         pr_err("IMC: Unable to stop the counters for core %d\n", core_id);
717                         return;
718                 }
719         } else if (ref->refc < 0) {
720                 WARN(1, "core-imc: Invalid event reference count\n");
721                 ref->refc = 0;
722         }
723         mutex_unlock(&ref->lock);
724 }
725
726 static int core_imc_event_init(struct perf_event *event)
727 {
728         int core_id, rc;
729         u64 config = event->attr.config;
730         struct imc_mem_info *pcmi;
731         struct imc_pmu *pmu;
732         struct imc_pmu_ref *ref;
733
734         if (event->attr.type != event->pmu->type)
735                 return -ENOENT;
736
737         /* Sampling not supported */
738         if (event->hw.sample_period)
739                 return -EINVAL;
740
741         /* unsupported modes and filters */
742         if (event->attr.exclude_user   ||
743             event->attr.exclude_kernel ||
744             event->attr.exclude_hv     ||
745             event->attr.exclude_idle   ||
746             event->attr.exclude_host   ||
747             event->attr.exclude_guest)
748                 return -EINVAL;
749
750         if (event->cpu < 0)
751                 return -EINVAL;
752
753         event->hw.idx = -1;
754         pmu = imc_event_to_pmu(event);
755
756         /* Sanity check for config (event offset) */
757         if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
758                 return -EINVAL;
759
760         if (!is_core_imc_mem_inited(event->cpu))
761                 return -ENODEV;
762
763         core_id = event->cpu / threads_per_core;
764         pcmi = &core_imc_pmu->mem_info[core_id];
765         if ((!pcmi->vbase))
766                 return -ENODEV;
767
768         /* Get the core_imc mutex for this core */
769         ref = &core_imc_refc[core_id];
770         if (!ref)
771                 return -EINVAL;
772
773         /*
774          * Core pmu units are enabled only when it is used.
775          * See if this is triggered for the first time.
776          * If yes, take the mutex lock and enable the core counters.
777          * If not, just increment the count in core_imc_refc struct.
778          */
779         mutex_lock(&ref->lock);
780         if (ref->refc == 0) {
781                 rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
782                                              get_hard_smp_processor_id(event->cpu));
783                 if (rc) {
784                         mutex_unlock(&ref->lock);
785                         pr_err("core-imc: Unable to start the counters for core %d\n",
786                                                                         core_id);
787                         return rc;
788                 }
789         }
790         ++ref->refc;
791         mutex_unlock(&ref->lock);
792
793         event->hw.event_base = (u64)pcmi->vbase + (config & IMC_EVENT_OFFSET_MASK);
794         event->destroy = core_imc_counters_release;
795         return 0;
796 }
797
798 /*
799  * Allocates a page of memory for each of the online cpus, and write the
800  * physical base address of that page to the LDBAR for that cpu.
801  *
802  * LDBAR Register Layout:
803  *
804  *  0          4         8         12        16        20        24        28
805  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
806  *   | |       [   ]    [                   Counter Address [8:50]
807  *   | * Mode    |
808  *   |           * PB Scope
809  *   * Enable/Disable
810  *
811  *  32        36        40        44        48        52        56        60
812  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
813  *           Counter Address [8:50]              ]
814  *
815  */
816 static int thread_imc_mem_alloc(int cpu_id, int size)
817 {
818         u64 ldbar_value, *local_mem = per_cpu(thread_imc_mem, cpu_id);
819         int nid = cpu_to_node(cpu_id);
820
821         if (!local_mem) {
822                 /*
823                  * This case could happen only once at start, since we dont
824                  * free the memory in cpu offline path.
825                  */
826                 local_mem = page_address(alloc_pages_node(nid,
827                                   GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
828                                   __GFP_NOWARN, get_order(size)));
829                 if (!local_mem)
830                         return -ENOMEM;
831
832                 per_cpu(thread_imc_mem, cpu_id) = local_mem;
833         }
834
835         ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | THREAD_IMC_ENABLE;
836
837         mtspr(SPRN_LDBAR, ldbar_value);
838         return 0;
839 }
840
841 static int ppc_thread_imc_cpu_online(unsigned int cpu)
842 {
843         return thread_imc_mem_alloc(cpu, thread_imc_mem_size);
844 }
845
846 static int ppc_thread_imc_cpu_offline(unsigned int cpu)
847 {
848         mtspr(SPRN_LDBAR, 0);
849         return 0;
850 }
851
852 static int thread_imc_cpu_init(void)
853 {
854         return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE,
855                           "perf/powerpc/imc_thread:online",
856                           ppc_thread_imc_cpu_online,
857                           ppc_thread_imc_cpu_offline);
858 }
859
860 void thread_imc_pmu_sched_task(struct perf_event_context *ctx,
861                                       bool sched_in)
862 {
863         int core_id;
864         struct imc_pmu_ref *ref;
865
866         if (!is_core_imc_mem_inited(smp_processor_id()))
867                 return;
868
869         core_id = smp_processor_id() / threads_per_core;
870         /*
871          * imc pmus are enabled only when it is used.
872          * See if this is triggered for the first time.
873          * If yes, take the mutex lock and enable the counters.
874          * If not, just increment the count in ref count struct.
875          */
876         ref = &core_imc_refc[core_id];
877         if (!ref)
878                 return;
879
880         if (sched_in) {
881                 mutex_lock(&ref->lock);
882                 if (ref->refc == 0) {
883                         if (opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
884                              get_hard_smp_processor_id(smp_processor_id()))) {
885                                 mutex_unlock(&ref->lock);
886                                 pr_err("thread-imc: Unable to start the counter\
887                                                         for core %d\n", core_id);
888                                 return;
889                         }
890                 }
891                 ++ref->refc;
892                 mutex_unlock(&ref->lock);
893         } else {
894                 mutex_lock(&ref->lock);
895                 ref->refc--;
896                 if (ref->refc == 0) {
897                         if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
898                             get_hard_smp_processor_id(smp_processor_id()))) {
899                                 mutex_unlock(&ref->lock);
900                                 pr_err("thread-imc: Unable to stop the counters\
901                                                         for core %d\n", core_id);
902                                 return;
903                         }
904                 } else if (ref->refc < 0) {
905                         ref->refc = 0;
906                 }
907                 mutex_unlock(&ref->lock);
908         }
909
910         return;
911 }
912
913 static int thread_imc_event_init(struct perf_event *event)
914 {
915         u32 config = event->attr.config;
916         struct task_struct *target;
917         struct imc_pmu *pmu;
918
919         if (event->attr.type != event->pmu->type)
920                 return -ENOENT;
921
922         /* Sampling not supported */
923         if (event->hw.sample_period)
924                 return -EINVAL;
925
926         event->hw.idx = -1;
927         pmu = imc_event_to_pmu(event);
928
929         /* Sanity check for config offset */
930         if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
931                 return -EINVAL;
932
933         target = event->hw.target;
934         if (!target)
935                 return -EINVAL;
936
937         event->pmu->task_ctx_nr = perf_sw_context;
938         return 0;
939 }
940
941 static bool is_thread_imc_pmu(struct perf_event *event)
942 {
943         if (!strncmp(event->pmu->name, "thread_imc", strlen("thread_imc")))
944                 return true;
945
946         return false;
947 }
948
949 static u64 * get_event_base_addr(struct perf_event *event)
950 {
951         u64 addr;
952
953         if (is_thread_imc_pmu(event)) {
954                 addr = (u64)per_cpu(thread_imc_mem, smp_processor_id());
955                 return (u64 *)(addr + (event->attr.config & IMC_EVENT_OFFSET_MASK));
956         }
957
958         return (u64 *)event->hw.event_base;
959 }
960
961 static void thread_imc_pmu_start_txn(struct pmu *pmu,
962                                      unsigned int txn_flags)
963 {
964         if (txn_flags & ~PERF_PMU_TXN_ADD)
965                 return;
966         perf_pmu_disable(pmu);
967 }
968
969 static void thread_imc_pmu_cancel_txn(struct pmu *pmu)
970 {
971         perf_pmu_enable(pmu);
972 }
973
974 static int thread_imc_pmu_commit_txn(struct pmu *pmu)
975 {
976         perf_pmu_enable(pmu);
977         return 0;
978 }
979
980 static u64 imc_read_counter(struct perf_event *event)
981 {
982         u64 *addr, data;
983
984         /*
985          * In-Memory Collection (IMC) counters are free flowing counters.
986          * So we take a snapshot of the counter value on enable and save it
987          * to calculate the delta at later stage to present the event counter
988          * value.
989          */
990         addr = get_event_base_addr(event);
991         data = be64_to_cpu(READ_ONCE(*addr));
992         local64_set(&event->hw.prev_count, data);
993
994         return data;
995 }
996
997 static void imc_event_update(struct perf_event *event)
998 {
999         u64 counter_prev, counter_new, final_count;
1000
1001         counter_prev = local64_read(&event->hw.prev_count);
1002         counter_new = imc_read_counter(event);
1003         final_count = counter_new - counter_prev;
1004
1005         /* Update the delta to the event count */
1006         local64_add(final_count, &event->count);
1007 }
1008
1009 static void imc_event_start(struct perf_event *event, int flags)
1010 {
1011         /*
1012          * In Memory Counters are free flowing counters. HW or the microcode
1013          * keeps adding to the counter offset in memory. To get event
1014          * counter value, we snapshot the value here and we calculate
1015          * delta at later point.
1016          */
1017         imc_read_counter(event);
1018 }
1019
1020 static void imc_event_stop(struct perf_event *event, int flags)
1021 {
1022         /*
1023          * Take a snapshot and calculate the delta and update
1024          * the event counter values.
1025          */
1026         imc_event_update(event);
1027 }
1028
1029 static int imc_event_add(struct perf_event *event, int flags)
1030 {
1031         if (flags & PERF_EF_START)
1032                 imc_event_start(event, flags);
1033
1034         return 0;
1035 }
1036
1037 static int thread_imc_event_add(struct perf_event *event, int flags)
1038 {
1039         if (flags & PERF_EF_START)
1040                 imc_event_start(event, flags);
1041
1042         /* Enable the sched_task to start the engine */
1043         perf_sched_cb_inc(event->ctx->pmu);
1044         return 0;
1045 }
1046
1047 static void thread_imc_event_del(struct perf_event *event, int flags)
1048 {
1049         /*
1050          * Take a snapshot and calculate the delta and update
1051          * the event counter values.
1052          */
1053         imc_event_update(event);
1054         perf_sched_cb_dec(event->ctx->pmu);
1055 }
1056
1057 /* update_pmu_ops : Populate the appropriate operations for "pmu" */
1058 static int update_pmu_ops(struct imc_pmu *pmu)
1059 {
1060         pmu->pmu.task_ctx_nr = perf_invalid_context;
1061         pmu->pmu.add = imc_event_add;
1062         pmu->pmu.del = imc_event_stop;
1063         pmu->pmu.start = imc_event_start;
1064         pmu->pmu.stop = imc_event_stop;
1065         pmu->pmu.read = imc_event_update;
1066         pmu->pmu.attr_groups = pmu->attr_groups;
1067         pmu->attr_groups[IMC_FORMAT_ATTR] = &imc_format_group;
1068
1069         switch (pmu->domain) {
1070         case IMC_DOMAIN_NEST:
1071                 pmu->pmu.event_init = nest_imc_event_init;
1072                 pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1073                 break;
1074         case IMC_DOMAIN_CORE:
1075                 pmu->pmu.event_init = core_imc_event_init;
1076                 pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1077                 break;
1078         case IMC_DOMAIN_THREAD:
1079                 pmu->pmu.event_init = thread_imc_event_init;
1080                 pmu->pmu.sched_task = thread_imc_pmu_sched_task;
1081                 pmu->pmu.add = thread_imc_event_add;
1082                 pmu->pmu.del = thread_imc_event_del;
1083                 pmu->pmu.start_txn = thread_imc_pmu_start_txn;
1084                 pmu->pmu.cancel_txn = thread_imc_pmu_cancel_txn;
1085                 pmu->pmu.commit_txn = thread_imc_pmu_commit_txn;
1086                 break;
1087         default:
1088                 break;
1089         }
1090
1091         return 0;
1092 }
1093
1094 /* init_nest_pmu_ref: Initialize the imc_pmu_ref struct for all the nodes */
1095 static int init_nest_pmu_ref(void)
1096 {
1097         int nid, i, cpu;
1098
1099         nest_imc_refc = kcalloc(num_possible_nodes(), sizeof(*nest_imc_refc),
1100                                                                 GFP_KERNEL);
1101
1102         if (!nest_imc_refc)
1103                 return -ENOMEM;
1104
1105         i = 0;
1106         for_each_node(nid) {
1107                 /*
1108                  * Mutex lock to avoid races while tracking the number of
1109                  * sessions using the chip's nest pmu units.
1110                  */
1111                 mutex_init(&nest_imc_refc[i].lock);
1112
1113                 /*
1114                  * Loop to init the "id" with the node_id. Variable "i" initialized to
1115                  * 0 and will be used as index to the array. "i" will not go off the
1116                  * end of the array since the "for_each_node" loops for "N_POSSIBLE"
1117                  * nodes only.
1118                  */
1119                 nest_imc_refc[i++].id = nid;
1120         }
1121
1122         /*
1123          * Loop to init the per_cpu "local_nest_imc_refc" with the proper
1124          * "nest_imc_refc" index. This makes get_nest_pmu_ref() alot simple.
1125          */
1126         for_each_possible_cpu(cpu) {
1127                 nid = cpu_to_node(cpu);
1128                 for (i = 0; i < num_possible_nodes(); i++) {
1129                         if (nest_imc_refc[i].id == nid) {
1130                                 per_cpu(local_nest_imc_refc, cpu) = &nest_imc_refc[i];
1131                                 break;
1132                         }
1133                 }
1134         }
1135         return 0;
1136 }
1137
1138 static void cleanup_all_core_imc_memory(void)
1139 {
1140         int i, nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1141         struct imc_mem_info *ptr = core_imc_pmu->mem_info;
1142         int size = core_imc_pmu->counter_mem_size;
1143
1144         /* mem_info will never be NULL */
1145         for (i = 0; i < nr_cores; i++) {
1146                 if (ptr[i].vbase)
1147                         free_pages((u64)ptr->vbase, get_order(size));
1148         }
1149
1150         kfree(ptr);
1151         kfree(core_imc_refc);
1152 }
1153
1154 static void thread_imc_ldbar_disable(void *dummy)
1155 {
1156         /*
1157          * By Zeroing LDBAR, we disable thread-imc
1158          * updates.
1159          */
1160         mtspr(SPRN_LDBAR, 0);
1161 }
1162
1163 void thread_imc_disable(void)
1164 {
1165         on_each_cpu(thread_imc_ldbar_disable, NULL, 1);
1166 }
1167
1168 static void cleanup_all_thread_imc_memory(void)
1169 {
1170         int i, order = get_order(thread_imc_mem_size);
1171
1172         for_each_online_cpu(i) {
1173                 if (per_cpu(thread_imc_mem, i))
1174                         free_pages((u64)per_cpu(thread_imc_mem, i), order);
1175
1176         }
1177 }
1178
1179 /*
1180  * Common function to unregister cpu hotplug callback and
1181  * free the memory.
1182  * TODO: Need to handle pmu unregistering, which will be
1183  * done in followup series.
1184  */
1185 static void imc_common_cpuhp_mem_free(struct imc_pmu *pmu_ptr)
1186 {
1187         if (pmu_ptr->domain == IMC_DOMAIN_NEST) {
1188                 mutex_lock(&nest_init_lock);
1189                 if (nest_pmus == 1) {
1190                         cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE);
1191                         kfree(nest_imc_refc);
1192                         kfree(per_nest_pmu_arr);
1193                 }
1194
1195                 if (nest_pmus > 0)
1196                         nest_pmus--;
1197                 mutex_unlock(&nest_init_lock);
1198         }
1199
1200         /* Free core_imc memory */
1201         if (pmu_ptr->domain == IMC_DOMAIN_CORE) {
1202                 cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE);
1203                 cleanup_all_core_imc_memory();
1204         }
1205
1206         /* Free thread_imc memory */
1207         if (pmu_ptr->domain == IMC_DOMAIN_THREAD) {
1208                 cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE);
1209                 cleanup_all_thread_imc_memory();
1210         }
1211
1212         /* Only free the attr_groups which are dynamically allocated  */
1213         if (pmu_ptr->attr_groups[IMC_EVENT_ATTR])
1214                 kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]->attrs);
1215         kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]);
1216         kfree(pmu_ptr);
1217         return;
1218 }
1219
1220
1221 /*
1222  * imc_mem_init : Function to support memory allocation for core imc.
1223  */
1224 static int imc_mem_init(struct imc_pmu *pmu_ptr, struct device_node *parent,
1225                                                                 int pmu_index)
1226 {
1227         const char *s;
1228         int nr_cores, cpu, res;
1229
1230         if (of_property_read_string(parent, "name", &s))
1231                 return -ENODEV;
1232
1233         switch (pmu_ptr->domain) {
1234         case IMC_DOMAIN_NEST:
1235                 /* Update the pmu name */
1236                 pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s_imc", "nest_", s);
1237                 if (!pmu_ptr->pmu.name)
1238                         return -ENOMEM;
1239
1240                 /* Needed for hotplug/migration */
1241                 if (!per_nest_pmu_arr) {
1242                         per_nest_pmu_arr = kcalloc(get_max_nest_dev() + 1,
1243                                                 sizeof(struct imc_pmu *),
1244                                                 GFP_KERNEL);
1245                         if (!per_nest_pmu_arr)
1246                                 return -ENOMEM;
1247                 }
1248                 per_nest_pmu_arr[pmu_index] = pmu_ptr;
1249                 break;
1250         case IMC_DOMAIN_CORE:
1251                 /* Update the pmu name */
1252                 pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1253                 if (!pmu_ptr->pmu.name)
1254                         return -ENOMEM;
1255
1256                 nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1257                 pmu_ptr->mem_info = kcalloc(nr_cores, sizeof(struct imc_mem_info),
1258                                                                 GFP_KERNEL);
1259
1260                 if (!pmu_ptr->mem_info)
1261                         return -ENOMEM;
1262
1263                 core_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1264                                                                 GFP_KERNEL);
1265
1266                 if (!core_imc_refc)
1267                         return -ENOMEM;
1268
1269                 core_imc_pmu = pmu_ptr;
1270                 break;
1271         case IMC_DOMAIN_THREAD:
1272                 /* Update the pmu name */
1273                 pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1274                 if (!pmu_ptr->pmu.name)
1275                         return -ENOMEM;
1276
1277                 thread_imc_mem_size = pmu_ptr->counter_mem_size;
1278                 for_each_online_cpu(cpu) {
1279                         res = thread_imc_mem_alloc(cpu, pmu_ptr->counter_mem_size);
1280                         if (res)
1281                                 return res;
1282                 }
1283
1284                 thread_imc_pmu = pmu_ptr;
1285                 break;
1286         default:
1287                 return -EINVAL;
1288         }
1289
1290         return 0;
1291 }
1292
1293 /*
1294  * init_imc_pmu : Setup and register the IMC pmu device.
1295  *
1296  * @parent:     Device tree unit node
1297  * @pmu_ptr:    memory allocated for this pmu
1298  * @pmu_idx:    Count of nest pmc registered
1299  *
1300  * init_imc_pmu() setup pmu cpumask and registers for a cpu hotplug callback.
1301  * Handles failure cases and accordingly frees memory.
1302  */
1303 int init_imc_pmu(struct device_node *parent, struct imc_pmu *pmu_ptr, int pmu_idx)
1304 {
1305         int ret;
1306
1307         ret = imc_mem_init(pmu_ptr, parent, pmu_idx);
1308         if (ret)
1309                 goto err_free;
1310
1311         switch (pmu_ptr->domain) {
1312         case IMC_DOMAIN_NEST:
1313                 /*
1314                 * Nest imc pmu need only one cpu per chip, we initialize the
1315                 * cpumask for the first nest imc pmu and use the same for the
1316                 * rest. To handle the cpuhotplug callback unregister, we track
1317                 * the number of nest pmus in "nest_pmus".
1318                 */
1319                 mutex_lock(&nest_init_lock);
1320                 if (nest_pmus == 0) {
1321                         ret = init_nest_pmu_ref();
1322                         if (ret) {
1323                                 mutex_unlock(&nest_init_lock);
1324                                 goto err_free;
1325                         }
1326                         /* Register for cpu hotplug notification. */
1327                         ret = nest_pmu_cpumask_init();
1328                         if (ret) {
1329                                 mutex_unlock(&nest_init_lock);
1330                                 kfree(nest_imc_refc);
1331                                 kfree(per_nest_pmu_arr);
1332                                 goto err_free;
1333                         }
1334                 }
1335                 nest_pmus++;
1336                 mutex_unlock(&nest_init_lock);
1337                 break;
1338         case IMC_DOMAIN_CORE:
1339                 ret = core_imc_pmu_cpumask_init();
1340                 if (ret) {
1341                         cleanup_all_core_imc_memory();
1342                         return ret;
1343                 }
1344
1345                 break;
1346         case IMC_DOMAIN_THREAD:
1347                 ret = thread_imc_cpu_init();
1348                 if (ret) {
1349                         cleanup_all_thread_imc_memory();
1350                         return ret;
1351                 }
1352
1353                 break;
1354         default:
1355                 return  -1;     /* Unknown domain */
1356         }
1357
1358         ret = update_events_in_group(parent, pmu_ptr);
1359         if (ret)
1360                 goto err_free;
1361
1362         ret = update_pmu_ops(pmu_ptr);
1363         if (ret)
1364                 goto err_free;
1365
1366         ret = perf_pmu_register(&pmu_ptr->pmu, pmu_ptr->pmu.name, -1);
1367         if (ret)
1368                 goto err_free;
1369
1370         pr_info("%s performance monitor hardware support registered\n",
1371                                                         pmu_ptr->pmu.name);
1372
1373         return 0;
1374
1375 err_free:
1376         imc_common_cpuhp_mem_free(pmu_ptr);
1377         return ret;
1378 }