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