xref: /openbmc/linux/arch/powerpc/perf/imc-pmu.c (revision ff148d8a)
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 static 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 static 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 /* Trace IMC data structures */
47 static DEFINE_PER_CPU(u64 *, trace_imc_mem);
48 static struct imc_pmu_ref *trace_imc_refc;
49 static int trace_imc_mem_size;
50 
51 static struct imc_pmu *imc_event_to_pmu(struct perf_event *event)
52 {
53 	return container_of(event->pmu, struct imc_pmu, pmu);
54 }
55 
56 PMU_FORMAT_ATTR(event, "config:0-61");
57 PMU_FORMAT_ATTR(offset, "config:0-31");
58 PMU_FORMAT_ATTR(rvalue, "config:32");
59 PMU_FORMAT_ATTR(mode, "config:33-40");
60 static struct attribute *imc_format_attrs[] = {
61 	&format_attr_event.attr,
62 	&format_attr_offset.attr,
63 	&format_attr_rvalue.attr,
64 	&format_attr_mode.attr,
65 	NULL,
66 };
67 
68 static struct attribute_group imc_format_group = {
69 	.name = "format",
70 	.attrs = imc_format_attrs,
71 };
72 
73 /* Format attribute for imc trace-mode */
74 PMU_FORMAT_ATTR(cpmc_reserved, "config:0-19");
75 PMU_FORMAT_ATTR(cpmc_event, "config:20-27");
76 PMU_FORMAT_ATTR(cpmc_samplesel, "config:28-29");
77 PMU_FORMAT_ATTR(cpmc_load, "config:30-61");
78 static struct attribute *trace_imc_format_attrs[] = {
79 	&format_attr_event.attr,
80 	&format_attr_cpmc_reserved.attr,
81 	&format_attr_cpmc_event.attr,
82 	&format_attr_cpmc_samplesel.attr,
83 	&format_attr_cpmc_load.attr,
84 	NULL,
85 };
86 
87 static struct attribute_group trace_imc_format_group = {
88 .name = "format",
89 .attrs = trace_imc_format_attrs,
90 };
91 
92 /* Get the cpumask printed to a buffer "buf" */
93 static ssize_t imc_pmu_cpumask_get_attr(struct device *dev,
94 					struct device_attribute *attr,
95 					char *buf)
96 {
97 	struct pmu *pmu = dev_get_drvdata(dev);
98 	struct imc_pmu *imc_pmu = container_of(pmu, struct imc_pmu, pmu);
99 	cpumask_t *active_mask;
100 
101 	switch(imc_pmu->domain){
102 	case IMC_DOMAIN_NEST:
103 		active_mask = &nest_imc_cpumask;
104 		break;
105 	case IMC_DOMAIN_CORE:
106 		active_mask = &core_imc_cpumask;
107 		break;
108 	default:
109 		return 0;
110 	}
111 
112 	return cpumap_print_to_pagebuf(true, buf, active_mask);
113 }
114 
115 static DEVICE_ATTR(cpumask, S_IRUGO, imc_pmu_cpumask_get_attr, NULL);
116 
117 static struct attribute *imc_pmu_cpumask_attrs[] = {
118 	&dev_attr_cpumask.attr,
119 	NULL,
120 };
121 
122 static struct attribute_group imc_pmu_cpumask_attr_group = {
123 	.attrs = imc_pmu_cpumask_attrs,
124 };
125 
126 /* device_str_attr_create : Populate event "name" and string "str" in attribute */
127 static struct attribute *device_str_attr_create(const char *name, const char *str)
128 {
129 	struct perf_pmu_events_attr *attr;
130 
131 	attr = kzalloc(sizeof(*attr), GFP_KERNEL);
132 	if (!attr)
133 		return NULL;
134 	sysfs_attr_init(&attr->attr.attr);
135 
136 	attr->event_str = str;
137 	attr->attr.attr.name = name;
138 	attr->attr.attr.mode = 0444;
139 	attr->attr.show = perf_event_sysfs_show;
140 
141 	return &attr->attr.attr;
142 }
143 
144 static int imc_parse_event(struct device_node *np, const char *scale,
145 				  const char *unit, const char *prefix,
146 				  u32 base, struct imc_events *event)
147 {
148 	const char *s;
149 	u32 reg;
150 
151 	if (of_property_read_u32(np, "reg", &reg))
152 		goto error;
153 	/* Add the base_reg value to the "reg" */
154 	event->value = base + reg;
155 
156 	if (of_property_read_string(np, "event-name", &s))
157 		goto error;
158 
159 	event->name = kasprintf(GFP_KERNEL, "%s%s", prefix, s);
160 	if (!event->name)
161 		goto error;
162 
163 	if (of_property_read_string(np, "scale", &s))
164 		s = scale;
165 
166 	if (s) {
167 		event->scale = kstrdup(s, GFP_KERNEL);
168 		if (!event->scale)
169 			goto error;
170 	}
171 
172 	if (of_property_read_string(np, "unit", &s))
173 		s = unit;
174 
175 	if (s) {
176 		event->unit = kstrdup(s, GFP_KERNEL);
177 		if (!event->unit)
178 			goto error;
179 	}
180 
181 	return 0;
182 error:
183 	kfree(event->unit);
184 	kfree(event->scale);
185 	kfree(event->name);
186 	return -EINVAL;
187 }
188 
189 /*
190  * imc_free_events: Function to cleanup the events list, having
191  * 		    "nr_entries".
192  */
193 static void imc_free_events(struct imc_events *events, int nr_entries)
194 {
195 	int i;
196 
197 	/* Nothing to clean, return */
198 	if (!events)
199 		return;
200 	for (i = 0; i < nr_entries; i++) {
201 		kfree(events[i].unit);
202 		kfree(events[i].scale);
203 		kfree(events[i].name);
204 	}
205 
206 	kfree(events);
207 }
208 
209 /*
210  * update_events_in_group: Update the "events" information in an attr_group
211  *                         and assign the attr_group to the pmu "pmu".
212  */
213 static int update_events_in_group(struct device_node *node, struct imc_pmu *pmu)
214 {
215 	struct attribute_group *attr_group;
216 	struct attribute **attrs, *dev_str;
217 	struct device_node *np, *pmu_events;
218 	u32 handle, base_reg;
219 	int i = 0, j = 0, ct, ret;
220 	const char *prefix, *g_scale, *g_unit;
221 	const char *ev_val_str, *ev_scale_str, *ev_unit_str;
222 
223 	if (!of_property_read_u32(node, "events", &handle))
224 		pmu_events = of_find_node_by_phandle(handle);
225 	else
226 		return 0;
227 
228 	/* Did not find any node with a given phandle */
229 	if (!pmu_events)
230 		return 0;
231 
232 	/* Get a count of number of child nodes */
233 	ct = of_get_child_count(pmu_events);
234 
235 	/* Get the event prefix */
236 	if (of_property_read_string(node, "events-prefix", &prefix))
237 		return 0;
238 
239 	/* Get a global unit and scale data if available */
240 	if (of_property_read_string(node, "scale", &g_scale))
241 		g_scale = NULL;
242 
243 	if (of_property_read_string(node, "unit", &g_unit))
244 		g_unit = NULL;
245 
246 	/* "reg" property gives out the base offset of the counters data */
247 	of_property_read_u32(node, "reg", &base_reg);
248 
249 	/* Allocate memory for the events */
250 	pmu->events = kcalloc(ct, sizeof(struct imc_events), GFP_KERNEL);
251 	if (!pmu->events)
252 		return -ENOMEM;
253 
254 	ct = 0;
255 	/* Parse the events and update the struct */
256 	for_each_child_of_node(pmu_events, np) {
257 		ret = imc_parse_event(np, g_scale, g_unit, prefix, base_reg, &pmu->events[ct]);
258 		if (!ret)
259 			ct++;
260 	}
261 
262 	/* Allocate memory for attribute group */
263 	attr_group = kzalloc(sizeof(*attr_group), GFP_KERNEL);
264 	if (!attr_group) {
265 		imc_free_events(pmu->events, ct);
266 		return -ENOMEM;
267 	}
268 
269 	/*
270 	 * Allocate memory for attributes.
271 	 * Since we have count of events for this pmu, we also allocate
272 	 * memory for the scale and unit attribute for now.
273 	 * "ct" has the total event structs added from the events-parent node.
274 	 * So allocate three times the "ct" (this includes event, event_scale and
275 	 * event_unit).
276 	 */
277 	attrs = kcalloc(((ct * 3) + 1), sizeof(struct attribute *), GFP_KERNEL);
278 	if (!attrs) {
279 		kfree(attr_group);
280 		imc_free_events(pmu->events, ct);
281 		return -ENOMEM;
282 	}
283 
284 	attr_group->name = "events";
285 	attr_group->attrs = attrs;
286 	do {
287 		ev_val_str = kasprintf(GFP_KERNEL, "event=0x%x", pmu->events[i].value);
288 		dev_str = device_str_attr_create(pmu->events[i].name, ev_val_str);
289 		if (!dev_str)
290 			continue;
291 
292 		attrs[j++] = dev_str;
293 		if (pmu->events[i].scale) {
294 			ev_scale_str = kasprintf(GFP_KERNEL, "%s.scale", pmu->events[i].name);
295 			dev_str = device_str_attr_create(ev_scale_str, pmu->events[i].scale);
296 			if (!dev_str)
297 				continue;
298 
299 			attrs[j++] = dev_str;
300 		}
301 
302 		if (pmu->events[i].unit) {
303 			ev_unit_str = kasprintf(GFP_KERNEL, "%s.unit", pmu->events[i].name);
304 			dev_str = device_str_attr_create(ev_unit_str, pmu->events[i].unit);
305 			if (!dev_str)
306 				continue;
307 
308 			attrs[j++] = dev_str;
309 		}
310 	} while (++i < ct);
311 
312 	/* Save the event attribute */
313 	pmu->attr_groups[IMC_EVENT_ATTR] = attr_group;
314 
315 	return 0;
316 }
317 
318 /* get_nest_pmu_ref: Return the imc_pmu_ref struct for the given node */
319 static struct imc_pmu_ref *get_nest_pmu_ref(int cpu)
320 {
321 	return per_cpu(local_nest_imc_refc, cpu);
322 }
323 
324 static void nest_change_cpu_context(int old_cpu, int new_cpu)
325 {
326 	struct imc_pmu **pn = per_nest_pmu_arr;
327 
328 	if (old_cpu < 0 || new_cpu < 0)
329 		return;
330 
331 	while (*pn) {
332 		perf_pmu_migrate_context(&(*pn)->pmu, old_cpu, new_cpu);
333 		pn++;
334 	}
335 }
336 
337 static int ppc_nest_imc_cpu_offline(unsigned int cpu)
338 {
339 	int nid, target = -1;
340 	const struct cpumask *l_cpumask;
341 	struct imc_pmu_ref *ref;
342 
343 	/*
344 	 * Check in the designated list for this cpu. Dont bother
345 	 * if not one of them.
346 	 */
347 	if (!cpumask_test_and_clear_cpu(cpu, &nest_imc_cpumask))
348 		return 0;
349 
350 	/*
351 	 * Check whether nest_imc is registered. We could end up here if the
352 	 * cpuhotplug callback registration fails. i.e, callback invokes the
353 	 * offline path for all successfully registered nodes. At this stage,
354 	 * nest_imc pmu will not be registered and we should return here.
355 	 *
356 	 * We return with a zero since this is not an offline failure. And
357 	 * cpuhp_setup_state() returns the actual failure reason to the caller,
358 	 * which in turn will call the cleanup routine.
359 	 */
360 	if (!nest_pmus)
361 		return 0;
362 
363 	/*
364 	 * Now that this cpu is one of the designated,
365 	 * find a next cpu a) which is online and b) in same chip.
366 	 */
367 	nid = cpu_to_node(cpu);
368 	l_cpumask = cpumask_of_node(nid);
369 	target = cpumask_any_but(l_cpumask, cpu);
370 
371 	/*
372 	 * Update the cpumask with the target cpu and
373 	 * migrate the context if needed
374 	 */
375 	if (target >= 0 && target < nr_cpu_ids) {
376 		cpumask_set_cpu(target, &nest_imc_cpumask);
377 		nest_change_cpu_context(cpu, target);
378 	} else {
379 		opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
380 				       get_hard_smp_processor_id(cpu));
381 		/*
382 		 * If this is the last cpu in this chip then, skip the reference
383 		 * count mutex lock and make the reference count on this chip zero.
384 		 */
385 		ref = get_nest_pmu_ref(cpu);
386 		if (!ref)
387 			return -EINVAL;
388 
389 		ref->refc = 0;
390 	}
391 	return 0;
392 }
393 
394 static int ppc_nest_imc_cpu_online(unsigned int cpu)
395 {
396 	const struct cpumask *l_cpumask;
397 	static struct cpumask tmp_mask;
398 	int res;
399 
400 	/* Get the cpumask of this node */
401 	l_cpumask = cpumask_of_node(cpu_to_node(cpu));
402 
403 	/*
404 	 * If this is not the first online CPU on this node, then
405 	 * just return.
406 	 */
407 	if (cpumask_and(&tmp_mask, l_cpumask, &nest_imc_cpumask))
408 		return 0;
409 
410 	/*
411 	 * If this is the first online cpu on this node
412 	 * disable the nest counters by making an OPAL call.
413 	 */
414 	res = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
415 				     get_hard_smp_processor_id(cpu));
416 	if (res)
417 		return res;
418 
419 	/* Make this CPU the designated target for counter collection */
420 	cpumask_set_cpu(cpu, &nest_imc_cpumask);
421 	return 0;
422 }
423 
424 static int nest_pmu_cpumask_init(void)
425 {
426 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE,
427 				 "perf/powerpc/imc:online",
428 				 ppc_nest_imc_cpu_online,
429 				 ppc_nest_imc_cpu_offline);
430 }
431 
432 static void nest_imc_counters_release(struct perf_event *event)
433 {
434 	int rc, node_id;
435 	struct imc_pmu_ref *ref;
436 
437 	if (event->cpu < 0)
438 		return;
439 
440 	node_id = cpu_to_node(event->cpu);
441 
442 	/*
443 	 * See if we need to disable the nest PMU.
444 	 * If no events are currently in use, then we have to take a
445 	 * mutex to ensure that we don't race with another task doing
446 	 * enable or disable the nest counters.
447 	 */
448 	ref = get_nest_pmu_ref(event->cpu);
449 	if (!ref)
450 		return;
451 
452 	/* Take the mutex lock for this node and then decrement the reference count */
453 	mutex_lock(&ref->lock);
454 	if (ref->refc == 0) {
455 		/*
456 		 * The scenario where this is true is, when perf session is
457 		 * started, followed by offlining of all cpus in a given node.
458 		 *
459 		 * In the cpuhotplug offline path, ppc_nest_imc_cpu_offline()
460 		 * function set the ref->count to zero, if the cpu which is
461 		 * about to offline is the last cpu in a given node and make
462 		 * an OPAL call to disable the engine in that node.
463 		 *
464 		 */
465 		mutex_unlock(&ref->lock);
466 		return;
467 	}
468 	ref->refc--;
469 	if (ref->refc == 0) {
470 		rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
471 					    get_hard_smp_processor_id(event->cpu));
472 		if (rc) {
473 			mutex_unlock(&ref->lock);
474 			pr_err("nest-imc: Unable to stop the counters for core %d\n", node_id);
475 			return;
476 		}
477 	} else if (ref->refc < 0) {
478 		WARN(1, "nest-imc: Invalid event reference count\n");
479 		ref->refc = 0;
480 	}
481 	mutex_unlock(&ref->lock);
482 }
483 
484 static int nest_imc_event_init(struct perf_event *event)
485 {
486 	int chip_id, rc, node_id;
487 	u32 l_config, config = event->attr.config;
488 	struct imc_mem_info *pcni;
489 	struct imc_pmu *pmu;
490 	struct imc_pmu_ref *ref;
491 	bool flag = false;
492 
493 	if (event->attr.type != event->pmu->type)
494 		return -ENOENT;
495 
496 	/* Sampling not supported */
497 	if (event->hw.sample_period)
498 		return -EINVAL;
499 
500 	if (event->cpu < 0)
501 		return -EINVAL;
502 
503 	pmu = imc_event_to_pmu(event);
504 
505 	/* Sanity check for config (event offset) */
506 	if ((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size)
507 		return -EINVAL;
508 
509 	/*
510 	 * Nest HW counter memory resides in a per-chip reserve-memory (HOMER).
511 	 * Get the base memory addresss for this cpu.
512 	 */
513 	chip_id = cpu_to_chip_id(event->cpu);
514 
515 	/* Return, if chip_id is not valid */
516 	if (chip_id < 0)
517 		return -ENODEV;
518 
519 	pcni = pmu->mem_info;
520 	do {
521 		if (pcni->id == chip_id) {
522 			flag = true;
523 			break;
524 		}
525 		pcni++;
526 	} while (pcni->vbase != 0);
527 
528 	if (!flag)
529 		return -ENODEV;
530 
531 	/*
532 	 * Add the event offset to the base address.
533 	 */
534 	l_config = config & IMC_EVENT_OFFSET_MASK;
535 	event->hw.event_base = (u64)pcni->vbase + l_config;
536 	node_id = cpu_to_node(event->cpu);
537 
538 	/*
539 	 * Get the imc_pmu_ref struct for this node.
540 	 * Take the mutex lock and then increment the count of nest pmu events
541 	 * inited.
542 	 */
543 	ref = get_nest_pmu_ref(event->cpu);
544 	if (!ref)
545 		return -EINVAL;
546 
547 	mutex_lock(&ref->lock);
548 	if (ref->refc == 0) {
549 		rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_NEST,
550 					     get_hard_smp_processor_id(event->cpu));
551 		if (rc) {
552 			mutex_unlock(&ref->lock);
553 			pr_err("nest-imc: Unable to start the counters for node %d\n",
554 									node_id);
555 			return rc;
556 		}
557 	}
558 	++ref->refc;
559 	mutex_unlock(&ref->lock);
560 
561 	event->destroy = nest_imc_counters_release;
562 	return 0;
563 }
564 
565 /*
566  * core_imc_mem_init : Initializes memory for the current core.
567  *
568  * Uses alloc_pages_node() and uses the returned address as an argument to
569  * an opal call to configure the pdbar. The address sent as an argument is
570  * converted to physical address before the opal call is made. This is the
571  * base address at which the core imc counters are populated.
572  */
573 static int core_imc_mem_init(int cpu, int size)
574 {
575 	int nid, rc = 0, core_id = (cpu / threads_per_core);
576 	struct imc_mem_info *mem_info;
577 
578 	/*
579 	 * alloc_pages_node() will allocate memory for core in the
580 	 * local node only.
581 	 */
582 	nid = cpu_to_node(cpu);
583 	mem_info = &core_imc_pmu->mem_info[core_id];
584 	mem_info->id = core_id;
585 
586 	/* We need only vbase for core counters */
587 	mem_info->vbase = page_address(alloc_pages_node(nid,
588 					  GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
589 					  __GFP_NOWARN, get_order(size)));
590 	if (!mem_info->vbase)
591 		return -ENOMEM;
592 
593 	/* Init the mutex */
594 	core_imc_refc[core_id].id = core_id;
595 	mutex_init(&core_imc_refc[core_id].lock);
596 
597 	rc = opal_imc_counters_init(OPAL_IMC_COUNTERS_CORE,
598 				__pa((void *)mem_info->vbase),
599 				get_hard_smp_processor_id(cpu));
600 	if (rc) {
601 		free_pages((u64)mem_info->vbase, get_order(size));
602 		mem_info->vbase = NULL;
603 	}
604 
605 	return rc;
606 }
607 
608 static bool is_core_imc_mem_inited(int cpu)
609 {
610 	struct imc_mem_info *mem_info;
611 	int core_id = (cpu / threads_per_core);
612 
613 	mem_info = &core_imc_pmu->mem_info[core_id];
614 	if (!mem_info->vbase)
615 		return false;
616 
617 	return true;
618 }
619 
620 static int ppc_core_imc_cpu_online(unsigned int cpu)
621 {
622 	const struct cpumask *l_cpumask;
623 	static struct cpumask tmp_mask;
624 	int ret = 0;
625 
626 	/* Get the cpumask for this core */
627 	l_cpumask = cpu_sibling_mask(cpu);
628 
629 	/* If a cpu for this core is already set, then, don't do anything */
630 	if (cpumask_and(&tmp_mask, l_cpumask, &core_imc_cpumask))
631 		return 0;
632 
633 	if (!is_core_imc_mem_inited(cpu)) {
634 		ret = core_imc_mem_init(cpu, core_imc_pmu->counter_mem_size);
635 		if (ret) {
636 			pr_info("core_imc memory allocation for cpu %d failed\n", cpu);
637 			return ret;
638 		}
639 	}
640 
641 	/* set the cpu in the mask */
642 	cpumask_set_cpu(cpu, &core_imc_cpumask);
643 	return 0;
644 }
645 
646 static int ppc_core_imc_cpu_offline(unsigned int cpu)
647 {
648 	unsigned int core_id;
649 	int ncpu;
650 	struct imc_pmu_ref *ref;
651 
652 	/*
653 	 * clear this cpu out of the mask, if not present in the mask,
654 	 * don't bother doing anything.
655 	 */
656 	if (!cpumask_test_and_clear_cpu(cpu, &core_imc_cpumask))
657 		return 0;
658 
659 	/*
660 	 * Check whether core_imc is registered. We could end up here
661 	 * if the cpuhotplug callback registration fails. i.e, callback
662 	 * invokes the offline path for all sucessfully registered cpus.
663 	 * At this stage, core_imc pmu will not be registered and we
664 	 * should return here.
665 	 *
666 	 * We return with a zero since this is not an offline failure.
667 	 * And cpuhp_setup_state() returns the actual failure reason
668 	 * to the caller, which inturn will call the cleanup routine.
669 	 */
670 	if (!core_imc_pmu->pmu.event_init)
671 		return 0;
672 
673 	/* Find any online cpu in that core except the current "cpu" */
674 	ncpu = cpumask_any_but(cpu_sibling_mask(cpu), cpu);
675 
676 	if (ncpu >= 0 && ncpu < nr_cpu_ids) {
677 		cpumask_set_cpu(ncpu, &core_imc_cpumask);
678 		perf_pmu_migrate_context(&core_imc_pmu->pmu, cpu, ncpu);
679 	} else {
680 		/*
681 		 * If this is the last cpu in this core then, skip taking refernce
682 		 * count mutex lock for this core and directly zero "refc" for
683 		 * this core.
684 		 */
685 		opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
686 				       get_hard_smp_processor_id(cpu));
687 		core_id = cpu / threads_per_core;
688 		ref = &core_imc_refc[core_id];
689 		if (!ref)
690 			return -EINVAL;
691 
692 		ref->refc = 0;
693 	}
694 	return 0;
695 }
696 
697 static int core_imc_pmu_cpumask_init(void)
698 {
699 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE,
700 				 "perf/powerpc/imc_core:online",
701 				 ppc_core_imc_cpu_online,
702 				 ppc_core_imc_cpu_offline);
703 }
704 
705 static void core_imc_counters_release(struct perf_event *event)
706 {
707 	int rc, core_id;
708 	struct imc_pmu_ref *ref;
709 
710 	if (event->cpu < 0)
711 		return;
712 	/*
713 	 * See if we need to disable the IMC PMU.
714 	 * If no events are currently in use, then we have to take a
715 	 * mutex to ensure that we don't race with another task doing
716 	 * enable or disable the core counters.
717 	 */
718 	core_id = event->cpu / threads_per_core;
719 
720 	/* Take the mutex lock and decrement the refernce count for this core */
721 	ref = &core_imc_refc[core_id];
722 	if (!ref)
723 		return;
724 
725 	mutex_lock(&ref->lock);
726 	if (ref->refc == 0) {
727 		/*
728 		 * The scenario where this is true is, when perf session is
729 		 * started, followed by offlining of all cpus in a given core.
730 		 *
731 		 * In the cpuhotplug offline path, ppc_core_imc_cpu_offline()
732 		 * function set the ref->count to zero, if the cpu which is
733 		 * about to offline is the last cpu in a given core and make
734 		 * an OPAL call to disable the engine in that core.
735 		 *
736 		 */
737 		mutex_unlock(&ref->lock);
738 		return;
739 	}
740 	ref->refc--;
741 	if (ref->refc == 0) {
742 		rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
743 					    get_hard_smp_processor_id(event->cpu));
744 		if (rc) {
745 			mutex_unlock(&ref->lock);
746 			pr_err("IMC: Unable to stop the counters for core %d\n", core_id);
747 			return;
748 		}
749 	} else if (ref->refc < 0) {
750 		WARN(1, "core-imc: Invalid event reference count\n");
751 		ref->refc = 0;
752 	}
753 	mutex_unlock(&ref->lock);
754 }
755 
756 static int core_imc_event_init(struct perf_event *event)
757 {
758 	int core_id, rc;
759 	u64 config = event->attr.config;
760 	struct imc_mem_info *pcmi;
761 	struct imc_pmu *pmu;
762 	struct imc_pmu_ref *ref;
763 
764 	if (event->attr.type != event->pmu->type)
765 		return -ENOENT;
766 
767 	/* Sampling not supported */
768 	if (event->hw.sample_period)
769 		return -EINVAL;
770 
771 	if (event->cpu < 0)
772 		return -EINVAL;
773 
774 	event->hw.idx = -1;
775 	pmu = imc_event_to_pmu(event);
776 
777 	/* Sanity check for config (event offset) */
778 	if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
779 		return -EINVAL;
780 
781 	if (!is_core_imc_mem_inited(event->cpu))
782 		return -ENODEV;
783 
784 	core_id = event->cpu / threads_per_core;
785 	pcmi = &core_imc_pmu->mem_info[core_id];
786 	if ((!pcmi->vbase))
787 		return -ENODEV;
788 
789 	/* Get the core_imc mutex for this core */
790 	ref = &core_imc_refc[core_id];
791 	if (!ref)
792 		return -EINVAL;
793 
794 	/*
795 	 * Core pmu units are enabled only when it is used.
796 	 * See if this is triggered for the first time.
797 	 * If yes, take the mutex lock and enable the core counters.
798 	 * If not, just increment the count in core_imc_refc struct.
799 	 */
800 	mutex_lock(&ref->lock);
801 	if (ref->refc == 0) {
802 		rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
803 					     get_hard_smp_processor_id(event->cpu));
804 		if (rc) {
805 			mutex_unlock(&ref->lock);
806 			pr_err("core-imc: Unable to start the counters for core %d\n",
807 									core_id);
808 			return rc;
809 		}
810 	}
811 	++ref->refc;
812 	mutex_unlock(&ref->lock);
813 
814 	event->hw.event_base = (u64)pcmi->vbase + (config & IMC_EVENT_OFFSET_MASK);
815 	event->destroy = core_imc_counters_release;
816 	return 0;
817 }
818 
819 /*
820  * Allocates a page of memory for each of the online cpus, and load
821  * LDBAR with 0.
822  * The physical base address of the page allocated for a cpu will be
823  * written to the LDBAR for that cpu, when the thread-imc event
824  * is added.
825  *
826  * LDBAR Register Layout:
827  *
828  *  0          4         8         12        16        20        24        28
829  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
830  *   | |       [   ]    [                   Counter Address [8:50]
831  *   | * Mode    |
832  *   |           * PB Scope
833  *   * Enable/Disable
834  *
835  *  32        36        40        44        48        52        56        60
836  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
837  *           Counter Address [8:50]              ]
838  *
839  */
840 static int thread_imc_mem_alloc(int cpu_id, int size)
841 {
842 	u64 *local_mem = per_cpu(thread_imc_mem, cpu_id);
843 	int nid = cpu_to_node(cpu_id);
844 
845 	if (!local_mem) {
846 		/*
847 		 * This case could happen only once at start, since we dont
848 		 * free the memory in cpu offline path.
849 		 */
850 		local_mem = page_address(alloc_pages_node(nid,
851 				  GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
852 				  __GFP_NOWARN, get_order(size)));
853 		if (!local_mem)
854 			return -ENOMEM;
855 
856 		per_cpu(thread_imc_mem, cpu_id) = local_mem;
857 	}
858 
859 	mtspr(SPRN_LDBAR, 0);
860 	return 0;
861 }
862 
863 static int ppc_thread_imc_cpu_online(unsigned int cpu)
864 {
865 	return thread_imc_mem_alloc(cpu, thread_imc_mem_size);
866 }
867 
868 static int ppc_thread_imc_cpu_offline(unsigned int cpu)
869 {
870 	mtspr(SPRN_LDBAR, 0);
871 	return 0;
872 }
873 
874 static int thread_imc_cpu_init(void)
875 {
876 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE,
877 			  "perf/powerpc/imc_thread:online",
878 			  ppc_thread_imc_cpu_online,
879 			  ppc_thread_imc_cpu_offline);
880 }
881 
882 static int thread_imc_event_init(struct perf_event *event)
883 {
884 	u32 config = event->attr.config;
885 	struct task_struct *target;
886 	struct imc_pmu *pmu;
887 
888 	if (event->attr.type != event->pmu->type)
889 		return -ENOENT;
890 
891 	if (!capable(CAP_SYS_ADMIN))
892 		return -EACCES;
893 
894 	/* Sampling not supported */
895 	if (event->hw.sample_period)
896 		return -EINVAL;
897 
898 	event->hw.idx = -1;
899 	pmu = imc_event_to_pmu(event);
900 
901 	/* Sanity check for config offset */
902 	if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
903 		return -EINVAL;
904 
905 	target = event->hw.target;
906 	if (!target)
907 		return -EINVAL;
908 
909 	event->pmu->task_ctx_nr = perf_sw_context;
910 	return 0;
911 }
912 
913 static bool is_thread_imc_pmu(struct perf_event *event)
914 {
915 	if (!strncmp(event->pmu->name, "thread_imc", strlen("thread_imc")))
916 		return true;
917 
918 	return false;
919 }
920 
921 static u64 * get_event_base_addr(struct perf_event *event)
922 {
923 	u64 addr;
924 
925 	if (is_thread_imc_pmu(event)) {
926 		addr = (u64)per_cpu(thread_imc_mem, smp_processor_id());
927 		return (u64 *)(addr + (event->attr.config & IMC_EVENT_OFFSET_MASK));
928 	}
929 
930 	return (u64 *)event->hw.event_base;
931 }
932 
933 static void thread_imc_pmu_start_txn(struct pmu *pmu,
934 				     unsigned int txn_flags)
935 {
936 	if (txn_flags & ~PERF_PMU_TXN_ADD)
937 		return;
938 	perf_pmu_disable(pmu);
939 }
940 
941 static void thread_imc_pmu_cancel_txn(struct pmu *pmu)
942 {
943 	perf_pmu_enable(pmu);
944 }
945 
946 static int thread_imc_pmu_commit_txn(struct pmu *pmu)
947 {
948 	perf_pmu_enable(pmu);
949 	return 0;
950 }
951 
952 static u64 imc_read_counter(struct perf_event *event)
953 {
954 	u64 *addr, data;
955 
956 	/*
957 	 * In-Memory Collection (IMC) counters are free flowing counters.
958 	 * So we take a snapshot of the counter value on enable and save it
959 	 * to calculate the delta at later stage to present the event counter
960 	 * value.
961 	 */
962 	addr = get_event_base_addr(event);
963 	data = be64_to_cpu(READ_ONCE(*addr));
964 	local64_set(&event->hw.prev_count, data);
965 
966 	return data;
967 }
968 
969 static void imc_event_update(struct perf_event *event)
970 {
971 	u64 counter_prev, counter_new, final_count;
972 
973 	counter_prev = local64_read(&event->hw.prev_count);
974 	counter_new = imc_read_counter(event);
975 	final_count = counter_new - counter_prev;
976 
977 	/* Update the delta to the event count */
978 	local64_add(final_count, &event->count);
979 }
980 
981 static void imc_event_start(struct perf_event *event, int flags)
982 {
983 	/*
984 	 * In Memory Counters are free flowing counters. HW or the microcode
985 	 * keeps adding to the counter offset in memory. To get event
986 	 * counter value, we snapshot the value here and we calculate
987 	 * delta at later point.
988 	 */
989 	imc_read_counter(event);
990 }
991 
992 static void imc_event_stop(struct perf_event *event, int flags)
993 {
994 	/*
995 	 * Take a snapshot and calculate the delta and update
996 	 * the event counter values.
997 	 */
998 	imc_event_update(event);
999 }
1000 
1001 static int imc_event_add(struct perf_event *event, int flags)
1002 {
1003 	if (flags & PERF_EF_START)
1004 		imc_event_start(event, flags);
1005 
1006 	return 0;
1007 }
1008 
1009 static int thread_imc_event_add(struct perf_event *event, int flags)
1010 {
1011 	int core_id;
1012 	struct imc_pmu_ref *ref;
1013 	u64 ldbar_value, *local_mem = per_cpu(thread_imc_mem, smp_processor_id());
1014 
1015 	if (flags & PERF_EF_START)
1016 		imc_event_start(event, flags);
1017 
1018 	if (!is_core_imc_mem_inited(smp_processor_id()))
1019 		return -EINVAL;
1020 
1021 	core_id = smp_processor_id() / threads_per_core;
1022 	ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | THREAD_IMC_ENABLE;
1023 	mtspr(SPRN_LDBAR, ldbar_value);
1024 
1025 	/*
1026 	 * imc pmus are enabled only when it is used.
1027 	 * See if this is triggered for the first time.
1028 	 * If yes, take the mutex lock and enable the counters.
1029 	 * If not, just increment the count in ref count struct.
1030 	 */
1031 	ref = &core_imc_refc[core_id];
1032 	if (!ref)
1033 		return -EINVAL;
1034 
1035 	mutex_lock(&ref->lock);
1036 	if (ref->refc == 0) {
1037 		if (opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
1038 		    get_hard_smp_processor_id(smp_processor_id()))) {
1039 			mutex_unlock(&ref->lock);
1040 			pr_err("thread-imc: Unable to start the counter\
1041 				for core %d\n", core_id);
1042 			return -EINVAL;
1043 		}
1044 	}
1045 	++ref->refc;
1046 	mutex_unlock(&ref->lock);
1047 	return 0;
1048 }
1049 
1050 static void thread_imc_event_del(struct perf_event *event, int flags)
1051 {
1052 
1053 	int core_id;
1054 	struct imc_pmu_ref *ref;
1055 
1056 	mtspr(SPRN_LDBAR, 0);
1057 
1058 	core_id = smp_processor_id() / threads_per_core;
1059 	ref = &core_imc_refc[core_id];
1060 
1061 	mutex_lock(&ref->lock);
1062 	ref->refc--;
1063 	if (ref->refc == 0) {
1064 		if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
1065 		    get_hard_smp_processor_id(smp_processor_id()))) {
1066 			mutex_unlock(&ref->lock);
1067 			pr_err("thread-imc: Unable to stop the counters\
1068 				for core %d\n", core_id);
1069 			return;
1070 		}
1071 	} else if (ref->refc < 0) {
1072 		ref->refc = 0;
1073 	}
1074 	mutex_unlock(&ref->lock);
1075 	/*
1076 	 * Take a snapshot and calculate the delta and update
1077 	 * the event counter values.
1078 	 */
1079 	imc_event_update(event);
1080 }
1081 
1082 /*
1083  * Allocate a page of memory for each cpu, and load LDBAR with 0.
1084  */
1085 static int trace_imc_mem_alloc(int cpu_id, int size)
1086 {
1087 	u64 *local_mem = per_cpu(trace_imc_mem, cpu_id);
1088 	int phys_id = cpu_to_node(cpu_id), rc = 0;
1089 	int core_id = (cpu_id / threads_per_core);
1090 
1091 	if (!local_mem) {
1092 		local_mem = page_address(alloc_pages_node(phys_id,
1093 					GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
1094 					__GFP_NOWARN, get_order(size)));
1095 		if (!local_mem)
1096 			return -ENOMEM;
1097 		per_cpu(trace_imc_mem, cpu_id) = local_mem;
1098 
1099 		/* Initialise the counters for trace mode */
1100 		rc = opal_imc_counters_init(OPAL_IMC_COUNTERS_TRACE, __pa((void *)local_mem),
1101 					    get_hard_smp_processor_id(cpu_id));
1102 		if (rc) {
1103 			pr_info("IMC:opal init failed for trace imc\n");
1104 			return rc;
1105 		}
1106 	}
1107 
1108 	/* Init the mutex, if not already */
1109 	trace_imc_refc[core_id].id = core_id;
1110 	mutex_init(&trace_imc_refc[core_id].lock);
1111 
1112 	mtspr(SPRN_LDBAR, 0);
1113 	return 0;
1114 }
1115 
1116 static int ppc_trace_imc_cpu_online(unsigned int cpu)
1117 {
1118 	return trace_imc_mem_alloc(cpu, trace_imc_mem_size);
1119 }
1120 
1121 static int ppc_trace_imc_cpu_offline(unsigned int cpu)
1122 {
1123 	mtspr(SPRN_LDBAR, 0);
1124 	return 0;
1125 }
1126 
1127 static int trace_imc_cpu_init(void)
1128 {
1129 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_TRACE_IMC_ONLINE,
1130 			  "perf/powerpc/imc_trace:online",
1131 			  ppc_trace_imc_cpu_online,
1132 			  ppc_trace_imc_cpu_offline);
1133 }
1134 
1135 static u64 get_trace_imc_event_base_addr(void)
1136 {
1137 	return (u64)per_cpu(trace_imc_mem, smp_processor_id());
1138 }
1139 
1140 /*
1141  * Function to parse trace-imc data obtained
1142  * and to prepare the perf sample.
1143  */
1144 static int trace_imc_prepare_sample(struct trace_imc_data *mem,
1145 				    struct perf_sample_data *data,
1146 				    u64 *prev_tb,
1147 				    struct perf_event_header *header,
1148 				    struct perf_event *event)
1149 {
1150 	/* Sanity checks for a valid record */
1151 	if (be64_to_cpu(READ_ONCE(mem->tb1)) > *prev_tb)
1152 		*prev_tb = be64_to_cpu(READ_ONCE(mem->tb1));
1153 	else
1154 		return -EINVAL;
1155 
1156 	if ((be64_to_cpu(READ_ONCE(mem->tb1)) & IMC_TRACE_RECORD_TB1_MASK) !=
1157 			 be64_to_cpu(READ_ONCE(mem->tb2)))
1158 		return -EINVAL;
1159 
1160 	/* Prepare perf sample */
1161 	data->ip =  be64_to_cpu(READ_ONCE(mem->ip));
1162 	data->period = event->hw.last_period;
1163 
1164 	header->type = PERF_RECORD_SAMPLE;
1165 	header->size = sizeof(*header) + event->header_size;
1166 	header->misc = 0;
1167 
1168 	if (is_kernel_addr(data->ip))
1169 		header->misc |= PERF_RECORD_MISC_KERNEL;
1170 	else
1171 		header->misc |= PERF_RECORD_MISC_USER;
1172 
1173 	perf_event_header__init_id(header, data, event);
1174 
1175 	return 0;
1176 }
1177 
1178 static void dump_trace_imc_data(struct perf_event *event)
1179 {
1180 	struct trace_imc_data *mem;
1181 	int i, ret;
1182 	u64 prev_tb = 0;
1183 
1184 	mem = (struct trace_imc_data *)get_trace_imc_event_base_addr();
1185 	for (i = 0; i < (trace_imc_mem_size / sizeof(struct trace_imc_data));
1186 		i++, mem++) {
1187 		struct perf_sample_data data;
1188 		struct perf_event_header header;
1189 
1190 		ret = trace_imc_prepare_sample(mem, &data, &prev_tb, &header, event);
1191 		if (ret) /* Exit, if not a valid record */
1192 			break;
1193 		else {
1194 			/* If this is a valid record, create the sample */
1195 			struct perf_output_handle handle;
1196 
1197 			if (perf_output_begin(&handle, event, header.size))
1198 				return;
1199 
1200 			perf_output_sample(&handle, &header, &data, event);
1201 			perf_output_end(&handle);
1202 		}
1203 	}
1204 }
1205 
1206 static int trace_imc_event_add(struct perf_event *event, int flags)
1207 {
1208 	int core_id = smp_processor_id() / threads_per_core;
1209 	struct imc_pmu_ref *ref = NULL;
1210 	u64 local_mem, ldbar_value;
1211 
1212 	/* Set trace-imc bit in ldbar and load ldbar with per-thread memory address */
1213 	local_mem = get_trace_imc_event_base_addr();
1214 	ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | TRACE_IMC_ENABLE;
1215 
1216 	if (core_imc_refc)
1217 		ref = &core_imc_refc[core_id];
1218 	if (!ref) {
1219 		/* If core-imc is not enabled, use trace-imc reference count */
1220 		if (trace_imc_refc)
1221 			ref = &trace_imc_refc[core_id];
1222 		if (!ref)
1223 			return -EINVAL;
1224 	}
1225 	mtspr(SPRN_LDBAR, ldbar_value);
1226 	mutex_lock(&ref->lock);
1227 	if (ref->refc == 0) {
1228 		if (opal_imc_counters_start(OPAL_IMC_COUNTERS_TRACE,
1229 				get_hard_smp_processor_id(smp_processor_id()))) {
1230 			mutex_unlock(&ref->lock);
1231 			pr_err("trace-imc: Unable to start the counters for core %d\n", core_id);
1232 			mtspr(SPRN_LDBAR, 0);
1233 			return -EINVAL;
1234 		}
1235 	}
1236 	++ref->refc;
1237 	mutex_unlock(&ref->lock);
1238 
1239 	return 0;
1240 }
1241 
1242 static void trace_imc_event_read(struct perf_event *event)
1243 {
1244 	return;
1245 }
1246 
1247 static void trace_imc_event_stop(struct perf_event *event, int flags)
1248 {
1249 	u64 local_mem = get_trace_imc_event_base_addr();
1250 	dump_trace_imc_data(event);
1251 	memset((void *)local_mem, 0, sizeof(u64));
1252 }
1253 
1254 static void trace_imc_event_start(struct perf_event *event, int flags)
1255 {
1256 	return;
1257 }
1258 
1259 static void trace_imc_event_del(struct perf_event *event, int flags)
1260 {
1261 	int core_id = smp_processor_id() / threads_per_core;
1262 	struct imc_pmu_ref *ref = NULL;
1263 
1264 	if (core_imc_refc)
1265 		ref = &core_imc_refc[core_id];
1266 	if (!ref) {
1267 		/* If core-imc is not enabled, use trace-imc reference count */
1268 		if (trace_imc_refc)
1269 			ref = &trace_imc_refc[core_id];
1270 		if (!ref)
1271 			return;
1272 	}
1273 	mtspr(SPRN_LDBAR, 0);
1274 	mutex_lock(&ref->lock);
1275 	ref->refc--;
1276 	if (ref->refc == 0) {
1277 		if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_TRACE,
1278 				get_hard_smp_processor_id(smp_processor_id()))) {
1279 			mutex_unlock(&ref->lock);
1280 			pr_err("trace-imc: Unable to stop the counters for core %d\n", core_id);
1281 			return;
1282 		}
1283 	} else if (ref->refc < 0) {
1284 		ref->refc = 0;
1285 	}
1286 	mutex_unlock(&ref->lock);
1287 	trace_imc_event_stop(event, flags);
1288 }
1289 
1290 static int trace_imc_event_init(struct perf_event *event)
1291 {
1292 	struct task_struct *target;
1293 
1294 	if (event->attr.type != event->pmu->type)
1295 		return -ENOENT;
1296 
1297 	if (!capable(CAP_SYS_ADMIN))
1298 		return -EACCES;
1299 
1300 	/* Return if this is a couting event */
1301 	if (event->attr.sample_period == 0)
1302 		return -ENOENT;
1303 
1304 	event->hw.idx = -1;
1305 	target = event->hw.target;
1306 
1307 	event->pmu->task_ctx_nr = perf_hw_context;
1308 	return 0;
1309 }
1310 
1311 /* update_pmu_ops : Populate the appropriate operations for "pmu" */
1312 static int update_pmu_ops(struct imc_pmu *pmu)
1313 {
1314 	pmu->pmu.task_ctx_nr = perf_invalid_context;
1315 	pmu->pmu.add = imc_event_add;
1316 	pmu->pmu.del = imc_event_stop;
1317 	pmu->pmu.start = imc_event_start;
1318 	pmu->pmu.stop = imc_event_stop;
1319 	pmu->pmu.read = imc_event_update;
1320 	pmu->pmu.attr_groups = pmu->attr_groups;
1321 	pmu->pmu.capabilities = PERF_PMU_CAP_NO_EXCLUDE;
1322 	pmu->attr_groups[IMC_FORMAT_ATTR] = &imc_format_group;
1323 
1324 	switch (pmu->domain) {
1325 	case IMC_DOMAIN_NEST:
1326 		pmu->pmu.event_init = nest_imc_event_init;
1327 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1328 		break;
1329 	case IMC_DOMAIN_CORE:
1330 		pmu->pmu.event_init = core_imc_event_init;
1331 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1332 		break;
1333 	case IMC_DOMAIN_THREAD:
1334 		pmu->pmu.event_init = thread_imc_event_init;
1335 		pmu->pmu.add = thread_imc_event_add;
1336 		pmu->pmu.del = thread_imc_event_del;
1337 		pmu->pmu.start_txn = thread_imc_pmu_start_txn;
1338 		pmu->pmu.cancel_txn = thread_imc_pmu_cancel_txn;
1339 		pmu->pmu.commit_txn = thread_imc_pmu_commit_txn;
1340 		break;
1341 	case IMC_DOMAIN_TRACE:
1342 		pmu->pmu.event_init = trace_imc_event_init;
1343 		pmu->pmu.add = trace_imc_event_add;
1344 		pmu->pmu.del = trace_imc_event_del;
1345 		pmu->pmu.start = trace_imc_event_start;
1346 		pmu->pmu.stop = trace_imc_event_stop;
1347 		pmu->pmu.read = trace_imc_event_read;
1348 		pmu->attr_groups[IMC_FORMAT_ATTR] = &trace_imc_format_group;
1349 	default:
1350 		break;
1351 	}
1352 
1353 	return 0;
1354 }
1355 
1356 /* init_nest_pmu_ref: Initialize the imc_pmu_ref struct for all the nodes */
1357 static int init_nest_pmu_ref(void)
1358 {
1359 	int nid, i, cpu;
1360 
1361 	nest_imc_refc = kcalloc(num_possible_nodes(), sizeof(*nest_imc_refc),
1362 								GFP_KERNEL);
1363 
1364 	if (!nest_imc_refc)
1365 		return -ENOMEM;
1366 
1367 	i = 0;
1368 	for_each_node(nid) {
1369 		/*
1370 		 * Mutex lock to avoid races while tracking the number of
1371 		 * sessions using the chip's nest pmu units.
1372 		 */
1373 		mutex_init(&nest_imc_refc[i].lock);
1374 
1375 		/*
1376 		 * Loop to init the "id" with the node_id. Variable "i" initialized to
1377 		 * 0 and will be used as index to the array. "i" will not go off the
1378 		 * end of the array since the "for_each_node" loops for "N_POSSIBLE"
1379 		 * nodes only.
1380 		 */
1381 		nest_imc_refc[i++].id = nid;
1382 	}
1383 
1384 	/*
1385 	 * Loop to init the per_cpu "local_nest_imc_refc" with the proper
1386 	 * "nest_imc_refc" index. This makes get_nest_pmu_ref() alot simple.
1387 	 */
1388 	for_each_possible_cpu(cpu) {
1389 		nid = cpu_to_node(cpu);
1390 		for (i = 0; i < num_possible_nodes(); i++) {
1391 			if (nest_imc_refc[i].id == nid) {
1392 				per_cpu(local_nest_imc_refc, cpu) = &nest_imc_refc[i];
1393 				break;
1394 			}
1395 		}
1396 	}
1397 	return 0;
1398 }
1399 
1400 static void cleanup_all_core_imc_memory(void)
1401 {
1402 	int i, nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1403 	struct imc_mem_info *ptr = core_imc_pmu->mem_info;
1404 	int size = core_imc_pmu->counter_mem_size;
1405 
1406 	/* mem_info will never be NULL */
1407 	for (i = 0; i < nr_cores; i++) {
1408 		if (ptr[i].vbase)
1409 			free_pages((u64)ptr[i].vbase, get_order(size));
1410 	}
1411 
1412 	kfree(ptr);
1413 	kfree(core_imc_refc);
1414 }
1415 
1416 static void thread_imc_ldbar_disable(void *dummy)
1417 {
1418 	/*
1419 	 * By Zeroing LDBAR, we disable thread-imc
1420 	 * updates.
1421 	 */
1422 	mtspr(SPRN_LDBAR, 0);
1423 }
1424 
1425 void thread_imc_disable(void)
1426 {
1427 	on_each_cpu(thread_imc_ldbar_disable, NULL, 1);
1428 }
1429 
1430 static void cleanup_all_thread_imc_memory(void)
1431 {
1432 	int i, order = get_order(thread_imc_mem_size);
1433 
1434 	for_each_online_cpu(i) {
1435 		if (per_cpu(thread_imc_mem, i))
1436 			free_pages((u64)per_cpu(thread_imc_mem, i), order);
1437 
1438 	}
1439 }
1440 
1441 static void cleanup_all_trace_imc_memory(void)
1442 {
1443 	int i, order = get_order(trace_imc_mem_size);
1444 
1445 	for_each_online_cpu(i) {
1446 		if (per_cpu(trace_imc_mem, i))
1447 			free_pages((u64)per_cpu(trace_imc_mem, i), order);
1448 
1449 	}
1450 	kfree(trace_imc_refc);
1451 }
1452 
1453 /* Function to free the attr_groups which are dynamically allocated */
1454 static void imc_common_mem_free(struct imc_pmu *pmu_ptr)
1455 {
1456 	if (pmu_ptr->attr_groups[IMC_EVENT_ATTR])
1457 		kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]->attrs);
1458 	kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]);
1459 }
1460 
1461 /*
1462  * Common function to unregister cpu hotplug callback and
1463  * free the memory.
1464  * TODO: Need to handle pmu unregistering, which will be
1465  * done in followup series.
1466  */
1467 static void imc_common_cpuhp_mem_free(struct imc_pmu *pmu_ptr)
1468 {
1469 	if (pmu_ptr->domain == IMC_DOMAIN_NEST) {
1470 		mutex_lock(&nest_init_lock);
1471 		if (nest_pmus == 1) {
1472 			cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE);
1473 			kfree(nest_imc_refc);
1474 			kfree(per_nest_pmu_arr);
1475 			per_nest_pmu_arr = NULL;
1476 		}
1477 
1478 		if (nest_pmus > 0)
1479 			nest_pmus--;
1480 		mutex_unlock(&nest_init_lock);
1481 	}
1482 
1483 	/* Free core_imc memory */
1484 	if (pmu_ptr->domain == IMC_DOMAIN_CORE) {
1485 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE);
1486 		cleanup_all_core_imc_memory();
1487 	}
1488 
1489 	/* Free thread_imc memory */
1490 	if (pmu_ptr->domain == IMC_DOMAIN_THREAD) {
1491 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE);
1492 		cleanup_all_thread_imc_memory();
1493 	}
1494 
1495 	if (pmu_ptr->domain == IMC_DOMAIN_TRACE) {
1496 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_TRACE_IMC_ONLINE);
1497 		cleanup_all_trace_imc_memory();
1498 	}
1499 }
1500 
1501 /*
1502  * Function to unregister thread-imc if core-imc
1503  * is not registered.
1504  */
1505 void unregister_thread_imc(void)
1506 {
1507 	imc_common_cpuhp_mem_free(thread_imc_pmu);
1508 	imc_common_mem_free(thread_imc_pmu);
1509 	perf_pmu_unregister(&thread_imc_pmu->pmu);
1510 }
1511 
1512 /*
1513  * imc_mem_init : Function to support memory allocation for core imc.
1514  */
1515 static int imc_mem_init(struct imc_pmu *pmu_ptr, struct device_node *parent,
1516 								int pmu_index)
1517 {
1518 	const char *s;
1519 	int nr_cores, cpu, res = -ENOMEM;
1520 
1521 	if (of_property_read_string(parent, "name", &s))
1522 		return -ENODEV;
1523 
1524 	switch (pmu_ptr->domain) {
1525 	case IMC_DOMAIN_NEST:
1526 		/* Update the pmu name */
1527 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s_imc", "nest_", s);
1528 		if (!pmu_ptr->pmu.name)
1529 			goto err;
1530 
1531 		/* Needed for hotplug/migration */
1532 		if (!per_nest_pmu_arr) {
1533 			per_nest_pmu_arr = kcalloc(get_max_nest_dev() + 1,
1534 						sizeof(struct imc_pmu *),
1535 						GFP_KERNEL);
1536 			if (!per_nest_pmu_arr)
1537 				goto err;
1538 		}
1539 		per_nest_pmu_arr[pmu_index] = pmu_ptr;
1540 		break;
1541 	case IMC_DOMAIN_CORE:
1542 		/* Update the pmu name */
1543 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1544 		if (!pmu_ptr->pmu.name)
1545 			goto err;
1546 
1547 		nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1548 		pmu_ptr->mem_info = kcalloc(nr_cores, sizeof(struct imc_mem_info),
1549 								GFP_KERNEL);
1550 
1551 		if (!pmu_ptr->mem_info)
1552 			goto err;
1553 
1554 		core_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1555 								GFP_KERNEL);
1556 
1557 		if (!core_imc_refc) {
1558 			kfree(pmu_ptr->mem_info);
1559 			goto err;
1560 		}
1561 
1562 		core_imc_pmu = pmu_ptr;
1563 		break;
1564 	case IMC_DOMAIN_THREAD:
1565 		/* Update the pmu name */
1566 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1567 		if (!pmu_ptr->pmu.name)
1568 			goto err;
1569 
1570 		thread_imc_mem_size = pmu_ptr->counter_mem_size;
1571 		for_each_online_cpu(cpu) {
1572 			res = thread_imc_mem_alloc(cpu, pmu_ptr->counter_mem_size);
1573 			if (res) {
1574 				cleanup_all_thread_imc_memory();
1575 				goto err;
1576 			}
1577 		}
1578 
1579 		thread_imc_pmu = pmu_ptr;
1580 		break;
1581 	case IMC_DOMAIN_TRACE:
1582 		/* Update the pmu name */
1583 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1584 		if (!pmu_ptr->pmu.name)
1585 			return -ENOMEM;
1586 
1587 		nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1588 		trace_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1589 								GFP_KERNEL);
1590 		if (!trace_imc_refc)
1591 			return -ENOMEM;
1592 
1593 		trace_imc_mem_size = pmu_ptr->counter_mem_size;
1594 		for_each_online_cpu(cpu) {
1595 			res = trace_imc_mem_alloc(cpu, trace_imc_mem_size);
1596 			if (res) {
1597 				cleanup_all_trace_imc_memory();
1598 				goto err;
1599 			}
1600 		}
1601 		break;
1602 	default:
1603 		return -EINVAL;
1604 	}
1605 
1606 	return 0;
1607 err:
1608 	return res;
1609 }
1610 
1611 /*
1612  * init_imc_pmu : Setup and register the IMC pmu device.
1613  *
1614  * @parent:	Device tree unit node
1615  * @pmu_ptr:	memory allocated for this pmu
1616  * @pmu_idx:	Count of nest pmc registered
1617  *
1618  * init_imc_pmu() setup pmu cpumask and registers for a cpu hotplug callback.
1619  * Handles failure cases and accordingly frees memory.
1620  */
1621 int init_imc_pmu(struct device_node *parent, struct imc_pmu *pmu_ptr, int pmu_idx)
1622 {
1623 	int ret;
1624 
1625 	ret = imc_mem_init(pmu_ptr, parent, pmu_idx);
1626 	if (ret)
1627 		goto err_free_mem;
1628 
1629 	switch (pmu_ptr->domain) {
1630 	case IMC_DOMAIN_NEST:
1631 		/*
1632 		* Nest imc pmu need only one cpu per chip, we initialize the
1633 		* cpumask for the first nest imc pmu and use the same for the
1634 		* rest. To handle the cpuhotplug callback unregister, we track
1635 		* the number of nest pmus in "nest_pmus".
1636 		*/
1637 		mutex_lock(&nest_init_lock);
1638 		if (nest_pmus == 0) {
1639 			ret = init_nest_pmu_ref();
1640 			if (ret) {
1641 				mutex_unlock(&nest_init_lock);
1642 				kfree(per_nest_pmu_arr);
1643 				per_nest_pmu_arr = NULL;
1644 				goto err_free_mem;
1645 			}
1646 			/* Register for cpu hotplug notification. */
1647 			ret = nest_pmu_cpumask_init();
1648 			if (ret) {
1649 				mutex_unlock(&nest_init_lock);
1650 				kfree(nest_imc_refc);
1651 				kfree(per_nest_pmu_arr);
1652 				per_nest_pmu_arr = NULL;
1653 				goto err_free_mem;
1654 			}
1655 		}
1656 		nest_pmus++;
1657 		mutex_unlock(&nest_init_lock);
1658 		break;
1659 	case IMC_DOMAIN_CORE:
1660 		ret = core_imc_pmu_cpumask_init();
1661 		if (ret) {
1662 			cleanup_all_core_imc_memory();
1663 			goto err_free_mem;
1664 		}
1665 
1666 		break;
1667 	case IMC_DOMAIN_THREAD:
1668 		ret = thread_imc_cpu_init();
1669 		if (ret) {
1670 			cleanup_all_thread_imc_memory();
1671 			goto err_free_mem;
1672 		}
1673 
1674 		break;
1675 	case IMC_DOMAIN_TRACE:
1676 		ret = trace_imc_cpu_init();
1677 		if (ret) {
1678 			cleanup_all_trace_imc_memory();
1679 			goto err_free_mem;
1680 		}
1681 
1682 		break;
1683 	default:
1684 		return  -EINVAL;	/* Unknown domain */
1685 	}
1686 
1687 	ret = update_events_in_group(parent, pmu_ptr);
1688 	if (ret)
1689 		goto err_free_cpuhp_mem;
1690 
1691 	ret = update_pmu_ops(pmu_ptr);
1692 	if (ret)
1693 		goto err_free_cpuhp_mem;
1694 
1695 	ret = perf_pmu_register(&pmu_ptr->pmu, pmu_ptr->pmu.name, -1);
1696 	if (ret)
1697 		goto err_free_cpuhp_mem;
1698 
1699 	pr_debug("%s performance monitor hardware support registered\n",
1700 							pmu_ptr->pmu.name);
1701 
1702 	return 0;
1703 
1704 err_free_cpuhp_mem:
1705 	imc_common_cpuhp_mem_free(pmu_ptr);
1706 err_free_mem:
1707 	imc_common_mem_free(pmu_ptr);
1708 	return ret;
1709 }
1710