xref: /linux/arch/powerpc/perf/imc-pmu.c (revision 5027ec19f1049a07df5b0a37b1f462514cf2724b)
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 cpumap_print_to_pagebuf(true, buf, 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(sizeof(*attr), GFP_KERNEL);
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 = kcalloc(ct, sizeof(struct imc_events), GFP_KERNEL);
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(sizeof(*attr_group), GFP_KERNEL);
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 = kcalloc(((ct * 3) + 1), sizeof(struct attribute *), GFP_KERNEL);
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 		dev_str = device_str_attr_create(pmu->events[i].name, ev_val_str);
303 		if (!dev_str)
304 			continue;
305 
306 		attrs[j++] = dev_str;
307 		if (pmu->events[i].scale) {
308 			ev_scale_str = kasprintf(GFP_KERNEL, "%s.scale", pmu->events[i].name);
309 			dev_str = device_str_attr_create(ev_scale_str, pmu->events[i].scale);
310 			if (!dev_str)
311 				continue;
312 
313 			attrs[j++] = dev_str;
314 		}
315 
316 		if (pmu->events[i].unit) {
317 			ev_unit_str = kasprintf(GFP_KERNEL, "%s.unit", pmu->events[i].name);
318 			dev_str = device_str_attr_create(ev_unit_str, pmu->events[i].unit);
319 			if (!dev_str)
320 				continue;
321 
322 			attrs[j++] = dev_str;
323 		}
324 	} while (++i < ct);
325 
326 	/* Save the event attribute */
327 	pmu->attr_groups[IMC_EVENT_ATTR] = attr_group;
328 
329 	return 0;
330 }
331 
332 /* get_nest_pmu_ref: Return the imc_pmu_ref struct for the given node */
333 static struct imc_pmu_ref *get_nest_pmu_ref(int cpu)
334 {
335 	return per_cpu(local_nest_imc_refc, cpu);
336 }
337 
338 static void nest_change_cpu_context(int old_cpu, int new_cpu)
339 {
340 	struct imc_pmu **pn = per_nest_pmu_arr;
341 
342 	if (old_cpu < 0 || new_cpu < 0)
343 		return;
344 
345 	while (*pn) {
346 		perf_pmu_migrate_context(&(*pn)->pmu, old_cpu, new_cpu);
347 		pn++;
348 	}
349 }
350 
351 static int ppc_nest_imc_cpu_offline(unsigned int cpu)
352 {
353 	int nid, target = -1;
354 	const struct cpumask *l_cpumask;
355 	struct imc_pmu_ref *ref;
356 
357 	/*
358 	 * Check in the designated list for this cpu. Dont bother
359 	 * if not one of them.
360 	 */
361 	if (!cpumask_test_and_clear_cpu(cpu, &nest_imc_cpumask))
362 		return 0;
363 
364 	/*
365 	 * Check whether nest_imc is registered. We could end up here if the
366 	 * cpuhotplug callback registration fails. i.e, callback invokes the
367 	 * offline path for all successfully registered nodes. At this stage,
368 	 * nest_imc pmu will not be registered and we should return here.
369 	 *
370 	 * We return with a zero since this is not an offline failure. And
371 	 * cpuhp_setup_state() returns the actual failure reason to the caller,
372 	 * which in turn will call the cleanup routine.
373 	 */
374 	if (!nest_pmus)
375 		return 0;
376 
377 	/*
378 	 * Now that this cpu is one of the designated,
379 	 * find a next cpu a) which is online and b) in same chip.
380 	 */
381 	nid = cpu_to_node(cpu);
382 	l_cpumask = cpumask_of_node(nid);
383 	target = cpumask_last(l_cpumask);
384 
385 	/*
386 	 * If this(target) is the last cpu in the cpumask for this chip,
387 	 * check for any possible online cpu in the chip.
388 	 */
389 	if (unlikely(target == cpu))
390 		target = cpumask_any_but(l_cpumask, cpu);
391 
392 	/*
393 	 * Update the cpumask with the target cpu and
394 	 * migrate the context if needed
395 	 */
396 	if (target >= 0 && target < nr_cpu_ids) {
397 		cpumask_set_cpu(target, &nest_imc_cpumask);
398 		nest_change_cpu_context(cpu, target);
399 	} else {
400 		opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
401 				       get_hard_smp_processor_id(cpu));
402 		/*
403 		 * If this is the last cpu in this chip then, skip the reference
404 		 * count lock and make the reference count on this chip zero.
405 		 */
406 		ref = get_nest_pmu_ref(cpu);
407 		if (!ref)
408 			return -EINVAL;
409 
410 		ref->refc = 0;
411 	}
412 	return 0;
413 }
414 
415 static int ppc_nest_imc_cpu_online(unsigned int cpu)
416 {
417 	const struct cpumask *l_cpumask;
418 	static struct cpumask tmp_mask;
419 	int res;
420 
421 	/* Get the cpumask of this node */
422 	l_cpumask = cpumask_of_node(cpu_to_node(cpu));
423 
424 	/*
425 	 * If this is not the first online CPU on this node, then
426 	 * just return.
427 	 */
428 	if (cpumask_and(&tmp_mask, l_cpumask, &nest_imc_cpumask))
429 		return 0;
430 
431 	/*
432 	 * If this is the first online cpu on this node
433 	 * disable the nest counters by making an OPAL call.
434 	 */
435 	res = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
436 				     get_hard_smp_processor_id(cpu));
437 	if (res)
438 		return res;
439 
440 	/* Make this CPU the designated target for counter collection */
441 	cpumask_set_cpu(cpu, &nest_imc_cpumask);
442 	return 0;
443 }
444 
445 static int nest_pmu_cpumask_init(void)
446 {
447 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE,
448 				 "perf/powerpc/imc:online",
449 				 ppc_nest_imc_cpu_online,
450 				 ppc_nest_imc_cpu_offline);
451 }
452 
453 static void nest_imc_counters_release(struct perf_event *event)
454 {
455 	int rc, node_id;
456 	struct imc_pmu_ref *ref;
457 
458 	if (event->cpu < 0)
459 		return;
460 
461 	node_id = cpu_to_node(event->cpu);
462 
463 	/*
464 	 * See if we need to disable the nest PMU.
465 	 * If no events are currently in use, then we have to take a
466 	 * lock to ensure that we don't race with another task doing
467 	 * enable or disable the nest counters.
468 	 */
469 	ref = get_nest_pmu_ref(event->cpu);
470 	if (!ref)
471 		return;
472 
473 	/* Take the lock for this node and then decrement the reference count */
474 	spin_lock(&ref->lock);
475 	if (ref->refc == 0) {
476 		/*
477 		 * The scenario where this is true is, when perf session is
478 		 * started, followed by offlining of all cpus in a given node.
479 		 *
480 		 * In the cpuhotplug offline path, ppc_nest_imc_cpu_offline()
481 		 * function set the ref->count to zero, if the cpu which is
482 		 * about to offline is the last cpu in a given node and make
483 		 * an OPAL call to disable the engine in that node.
484 		 *
485 		 */
486 		spin_unlock(&ref->lock);
487 		return;
488 	}
489 	ref->refc--;
490 	if (ref->refc == 0) {
491 		rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_NEST,
492 					    get_hard_smp_processor_id(event->cpu));
493 		if (rc) {
494 			spin_unlock(&ref->lock);
495 			pr_err("nest-imc: Unable to stop the counters for core %d\n", node_id);
496 			return;
497 		}
498 	} else if (ref->refc < 0) {
499 		WARN(1, "nest-imc: Invalid event reference count\n");
500 		ref->refc = 0;
501 	}
502 	spin_unlock(&ref->lock);
503 }
504 
505 static int nest_imc_event_init(struct perf_event *event)
506 {
507 	int chip_id, rc, node_id;
508 	u32 l_config, config = event->attr.config;
509 	struct imc_mem_info *pcni;
510 	struct imc_pmu *pmu;
511 	struct imc_pmu_ref *ref;
512 	bool flag = false;
513 
514 	if (event->attr.type != event->pmu->type)
515 		return -ENOENT;
516 
517 	/* Sampling not supported */
518 	if (event->hw.sample_period)
519 		return -EINVAL;
520 
521 	if (event->cpu < 0)
522 		return -EINVAL;
523 
524 	pmu = imc_event_to_pmu(event);
525 
526 	/* Sanity check for config (event offset) */
527 	if ((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size)
528 		return -EINVAL;
529 
530 	/*
531 	 * Nest HW counter memory resides in a per-chip reserve-memory (HOMER).
532 	 * Get the base memory address for this cpu.
533 	 */
534 	chip_id = cpu_to_chip_id(event->cpu);
535 
536 	/* Return, if chip_id is not valid */
537 	if (chip_id < 0)
538 		return -ENODEV;
539 
540 	pcni = pmu->mem_info;
541 	do {
542 		if (pcni->id == chip_id) {
543 			flag = true;
544 			break;
545 		}
546 		pcni++;
547 	} while (pcni->vbase);
548 
549 	if (!flag)
550 		return -ENODEV;
551 
552 	/*
553 	 * Add the event offset to the base address.
554 	 */
555 	l_config = config & IMC_EVENT_OFFSET_MASK;
556 	event->hw.event_base = (u64)pcni->vbase + l_config;
557 	node_id = cpu_to_node(event->cpu);
558 
559 	/*
560 	 * Get the imc_pmu_ref struct for this node.
561 	 * Take the lock and then increment the count of nest pmu events inited.
562 	 */
563 	ref = get_nest_pmu_ref(event->cpu);
564 	if (!ref)
565 		return -EINVAL;
566 
567 	spin_lock(&ref->lock);
568 	if (ref->refc == 0) {
569 		rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_NEST,
570 					     get_hard_smp_processor_id(event->cpu));
571 		if (rc) {
572 			spin_unlock(&ref->lock);
573 			pr_err("nest-imc: Unable to start the counters for node %d\n",
574 									node_id);
575 			return rc;
576 		}
577 	}
578 	++ref->refc;
579 	spin_unlock(&ref->lock);
580 
581 	event->destroy = nest_imc_counters_release;
582 	return 0;
583 }
584 
585 /*
586  * core_imc_mem_init : Initializes memory for the current core.
587  *
588  * Uses alloc_pages_node() and uses the returned address as an argument to
589  * an opal call to configure the pdbar. The address sent as an argument is
590  * converted to physical address before the opal call is made. This is the
591  * base address at which the core imc counters are populated.
592  */
593 static int core_imc_mem_init(int cpu, int size)
594 {
595 	int nid, rc = 0, core_id = (cpu / threads_per_core);
596 	struct imc_mem_info *mem_info;
597 	struct page *page;
598 
599 	/*
600 	 * alloc_pages_node() will allocate memory for core in the
601 	 * local node only.
602 	 */
603 	nid = cpu_to_node(cpu);
604 	mem_info = &core_imc_pmu->mem_info[core_id];
605 	mem_info->id = core_id;
606 
607 	/* We need only vbase for core counters */
608 	page = alloc_pages_node(nid,
609 				GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
610 				__GFP_NOWARN, get_order(size));
611 	if (!page)
612 		return -ENOMEM;
613 	mem_info->vbase = page_address(page);
614 
615 	core_imc_refc[core_id].id = core_id;
616 	spin_lock_init(&core_imc_refc[core_id].lock);
617 
618 	rc = opal_imc_counters_init(OPAL_IMC_COUNTERS_CORE,
619 				__pa((void *)mem_info->vbase),
620 				get_hard_smp_processor_id(cpu));
621 	if (rc) {
622 		free_pages((u64)mem_info->vbase, get_order(size));
623 		mem_info->vbase = NULL;
624 	}
625 
626 	return rc;
627 }
628 
629 static bool is_core_imc_mem_inited(int cpu)
630 {
631 	struct imc_mem_info *mem_info;
632 	int core_id = (cpu / threads_per_core);
633 
634 	mem_info = &core_imc_pmu->mem_info[core_id];
635 	if (!mem_info->vbase)
636 		return false;
637 
638 	return true;
639 }
640 
641 static int ppc_core_imc_cpu_online(unsigned int cpu)
642 {
643 	const struct cpumask *l_cpumask;
644 	static struct cpumask tmp_mask;
645 	int ret = 0;
646 
647 	/* Get the cpumask for this core */
648 	l_cpumask = cpu_sibling_mask(cpu);
649 
650 	/* If a cpu for this core is already set, then, don't do anything */
651 	if (cpumask_and(&tmp_mask, l_cpumask, &core_imc_cpumask))
652 		return 0;
653 
654 	if (!is_core_imc_mem_inited(cpu)) {
655 		ret = core_imc_mem_init(cpu, core_imc_pmu->counter_mem_size);
656 		if (ret) {
657 			pr_info("core_imc memory allocation for cpu %d failed\n", cpu);
658 			return ret;
659 		}
660 	}
661 
662 	/* set the cpu in the mask */
663 	cpumask_set_cpu(cpu, &core_imc_cpumask);
664 	return 0;
665 }
666 
667 static int ppc_core_imc_cpu_offline(unsigned int cpu)
668 {
669 	unsigned int core_id;
670 	int ncpu;
671 	struct imc_pmu_ref *ref;
672 
673 	/*
674 	 * clear this cpu out of the mask, if not present in the mask,
675 	 * don't bother doing anything.
676 	 */
677 	if (!cpumask_test_and_clear_cpu(cpu, &core_imc_cpumask))
678 		return 0;
679 
680 	/*
681 	 * Check whether core_imc is registered. We could end up here
682 	 * if the cpuhotplug callback registration fails. i.e, callback
683 	 * invokes the offline path for all successfully registered cpus.
684 	 * At this stage, core_imc pmu will not be registered and we
685 	 * should return here.
686 	 *
687 	 * We return with a zero since this is not an offline failure.
688 	 * And cpuhp_setup_state() returns the actual failure reason
689 	 * to the caller, which inturn will call the cleanup routine.
690 	 */
691 	if (!core_imc_pmu->pmu.event_init)
692 		return 0;
693 
694 	/* Find any online cpu in that core except the current "cpu" */
695 	ncpu = cpumask_last(cpu_sibling_mask(cpu));
696 
697 	if (unlikely(ncpu == cpu))
698 		ncpu = cpumask_any_but(cpu_sibling_mask(cpu), cpu);
699 
700 	if (ncpu >= 0 && ncpu < nr_cpu_ids) {
701 		cpumask_set_cpu(ncpu, &core_imc_cpumask);
702 		perf_pmu_migrate_context(&core_imc_pmu->pmu, cpu, ncpu);
703 	} else {
704 		/*
705 		 * If this is the last cpu in this core then skip taking reference
706 		 * count lock for this core and directly zero "refc" for this core.
707 		 */
708 		opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
709 				       get_hard_smp_processor_id(cpu));
710 		core_id = cpu / threads_per_core;
711 		ref = &core_imc_refc[core_id];
712 		if (!ref)
713 			return -EINVAL;
714 
715 		ref->refc = 0;
716 		/*
717 		 * Reduce the global reference count, if this is the
718 		 * last cpu in this core and core-imc event running
719 		 * in this cpu.
720 		 */
721 		spin_lock(&imc_global_refc.lock);
722 		if (imc_global_refc.id == IMC_DOMAIN_CORE)
723 			imc_global_refc.refc--;
724 
725 		spin_unlock(&imc_global_refc.lock);
726 	}
727 	return 0;
728 }
729 
730 static int core_imc_pmu_cpumask_init(void)
731 {
732 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE,
733 				 "perf/powerpc/imc_core:online",
734 				 ppc_core_imc_cpu_online,
735 				 ppc_core_imc_cpu_offline);
736 }
737 
738 static void reset_global_refc(struct perf_event *event)
739 {
740 		spin_lock(&imc_global_refc.lock);
741 		imc_global_refc.refc--;
742 
743 		/*
744 		 * If no other thread is running any
745 		 * event for this domain(thread/core/trace),
746 		 * set the global id to zero.
747 		 */
748 		if (imc_global_refc.refc <= 0) {
749 			imc_global_refc.refc = 0;
750 			imc_global_refc.id = 0;
751 		}
752 		spin_unlock(&imc_global_refc.lock);
753 }
754 
755 static void core_imc_counters_release(struct perf_event *event)
756 {
757 	int rc, core_id;
758 	struct imc_pmu_ref *ref;
759 
760 	if (event->cpu < 0)
761 		return;
762 	/*
763 	 * See if we need to disable the IMC PMU.
764 	 * If no events are currently in use, then we have to take a
765 	 * lock to ensure that we don't race with another task doing
766 	 * enable or disable the core counters.
767 	 */
768 	core_id = event->cpu / threads_per_core;
769 
770 	/* Take the lock and decrement the refernce count for this core */
771 	ref = &core_imc_refc[core_id];
772 	if (!ref)
773 		return;
774 
775 	spin_lock(&ref->lock);
776 	if (ref->refc == 0) {
777 		/*
778 		 * The scenario where this is true is, when perf session is
779 		 * started, followed by offlining of all cpus in a given core.
780 		 *
781 		 * In the cpuhotplug offline path, ppc_core_imc_cpu_offline()
782 		 * function set the ref->count to zero, if the cpu which is
783 		 * about to offline is the last cpu in a given core and make
784 		 * an OPAL call to disable the engine in that core.
785 		 *
786 		 */
787 		spin_unlock(&ref->lock);
788 		return;
789 	}
790 	ref->refc--;
791 	if (ref->refc == 0) {
792 		rc = opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
793 					    get_hard_smp_processor_id(event->cpu));
794 		if (rc) {
795 			spin_unlock(&ref->lock);
796 			pr_err("IMC: Unable to stop the counters for core %d\n", core_id);
797 			return;
798 		}
799 	} else if (ref->refc < 0) {
800 		WARN(1, "core-imc: Invalid event reference count\n");
801 		ref->refc = 0;
802 	}
803 	spin_unlock(&ref->lock);
804 
805 	reset_global_refc(event);
806 }
807 
808 static int core_imc_event_init(struct perf_event *event)
809 {
810 	int core_id, rc;
811 	u64 config = event->attr.config;
812 	struct imc_mem_info *pcmi;
813 	struct imc_pmu *pmu;
814 	struct imc_pmu_ref *ref;
815 
816 	if (event->attr.type != event->pmu->type)
817 		return -ENOENT;
818 
819 	/* Sampling not supported */
820 	if (event->hw.sample_period)
821 		return -EINVAL;
822 
823 	if (event->cpu < 0)
824 		return -EINVAL;
825 
826 	event->hw.idx = -1;
827 	pmu = imc_event_to_pmu(event);
828 
829 	/* Sanity check for config (event offset) */
830 	if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
831 		return -EINVAL;
832 
833 	if (!is_core_imc_mem_inited(event->cpu))
834 		return -ENODEV;
835 
836 	core_id = event->cpu / threads_per_core;
837 	pcmi = &core_imc_pmu->mem_info[core_id];
838 	if ((!pcmi->vbase))
839 		return -ENODEV;
840 
841 	ref = &core_imc_refc[core_id];
842 	if (!ref)
843 		return -EINVAL;
844 
845 	/*
846 	 * Core pmu units are enabled only when it is used.
847 	 * See if this is triggered for the first time.
848 	 * If yes, take the lock and enable the core counters.
849 	 * If not, just increment the count in core_imc_refc struct.
850 	 */
851 	spin_lock(&ref->lock);
852 	if (ref->refc == 0) {
853 		rc = opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
854 					     get_hard_smp_processor_id(event->cpu));
855 		if (rc) {
856 			spin_unlock(&ref->lock);
857 			pr_err("core-imc: Unable to start the counters for core %d\n",
858 									core_id);
859 			return rc;
860 		}
861 	}
862 	++ref->refc;
863 	spin_unlock(&ref->lock);
864 
865 	/*
866 	 * Since the system can run either in accumulation or trace-mode
867 	 * of IMC at a time, core-imc events are allowed only if no other
868 	 * trace/thread imc events are enabled/monitored.
869 	 *
870 	 * Take the global lock, and check the refc.id
871 	 * to know whether any other trace/thread imc
872 	 * events are running.
873 	 */
874 	spin_lock(&imc_global_refc.lock);
875 	if (imc_global_refc.id == 0 || imc_global_refc.id == IMC_DOMAIN_CORE) {
876 		/*
877 		 * No other trace/thread imc events are running in
878 		 * the system, so set the refc.id to core-imc.
879 		 */
880 		imc_global_refc.id = IMC_DOMAIN_CORE;
881 		imc_global_refc.refc++;
882 	} else {
883 		spin_unlock(&imc_global_refc.lock);
884 		return -EBUSY;
885 	}
886 	spin_unlock(&imc_global_refc.lock);
887 
888 	event->hw.event_base = (u64)pcmi->vbase + (config & IMC_EVENT_OFFSET_MASK);
889 	event->destroy = core_imc_counters_release;
890 	return 0;
891 }
892 
893 /*
894  * Allocates a page of memory for each of the online cpus, and load
895  * LDBAR with 0.
896  * The physical base address of the page allocated for a cpu will be
897  * written to the LDBAR for that cpu, when the thread-imc event
898  * is added.
899  *
900  * LDBAR Register Layout:
901  *
902  *  0          4         8         12        16        20        24        28
903  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
904  *   | |       [   ]    [                   Counter Address [8:50]
905  *   | * Mode    |
906  *   |           * PB Scope
907  *   * Enable/Disable
908  *
909  *  32        36        40        44        48        52        56        60
910  * | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - | - - - - |
911  *           Counter Address [8:50]              ]
912  *
913  */
914 static int thread_imc_mem_alloc(int cpu_id, int size)
915 {
916 	u64 *local_mem = per_cpu(thread_imc_mem, cpu_id);
917 	int nid = cpu_to_node(cpu_id);
918 
919 	if (!local_mem) {
920 		struct page *page;
921 		/*
922 		 * This case could happen only once at start, since we dont
923 		 * free the memory in cpu offline path.
924 		 */
925 		page = alloc_pages_node(nid,
926 				  GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
927 				  __GFP_NOWARN, get_order(size));
928 		if (!page)
929 			return -ENOMEM;
930 		local_mem = page_address(page);
931 
932 		per_cpu(thread_imc_mem, cpu_id) = local_mem;
933 	}
934 
935 	mtspr(SPRN_LDBAR, 0);
936 	return 0;
937 }
938 
939 static int ppc_thread_imc_cpu_online(unsigned int cpu)
940 {
941 	return thread_imc_mem_alloc(cpu, thread_imc_mem_size);
942 }
943 
944 static int ppc_thread_imc_cpu_offline(unsigned int cpu)
945 {
946 	/*
947 	 * Set the bit 0 of LDBAR to zero.
948 	 *
949 	 * If bit 0 of LDBAR is unset, it will stop posting
950 	 * the counter data to memory.
951 	 * For thread-imc, bit 0 of LDBAR will be set to 1 in the
952 	 * event_add function. So reset this bit here, to stop the updates
953 	 * to memory in the cpu_offline path.
954 	 */
955 	mtspr(SPRN_LDBAR, (mfspr(SPRN_LDBAR) & (~(1UL << 63))));
956 
957 	/* Reduce the refc if thread-imc event running on this cpu */
958 	spin_lock(&imc_global_refc.lock);
959 	if (imc_global_refc.id == IMC_DOMAIN_THREAD)
960 		imc_global_refc.refc--;
961 	spin_unlock(&imc_global_refc.lock);
962 
963 	return 0;
964 }
965 
966 static int thread_imc_cpu_init(void)
967 {
968 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE,
969 			  "perf/powerpc/imc_thread:online",
970 			  ppc_thread_imc_cpu_online,
971 			  ppc_thread_imc_cpu_offline);
972 }
973 
974 static int thread_imc_event_init(struct perf_event *event)
975 {
976 	u32 config = event->attr.config;
977 	struct task_struct *target;
978 	struct imc_pmu *pmu;
979 
980 	if (event->attr.type != event->pmu->type)
981 		return -ENOENT;
982 
983 	if (!perfmon_capable())
984 		return -EACCES;
985 
986 	/* Sampling not supported */
987 	if (event->hw.sample_period)
988 		return -EINVAL;
989 
990 	event->hw.idx = -1;
991 	pmu = imc_event_to_pmu(event);
992 
993 	/* Sanity check for config offset */
994 	if (((config & IMC_EVENT_OFFSET_MASK) > pmu->counter_mem_size))
995 		return -EINVAL;
996 
997 	target = event->hw.target;
998 	if (!target)
999 		return -EINVAL;
1000 
1001 	spin_lock(&imc_global_refc.lock);
1002 	/*
1003 	 * Check if any other trace/core imc events are running in the
1004 	 * system, if not set the global id to thread-imc.
1005 	 */
1006 	if (imc_global_refc.id == 0 || imc_global_refc.id == IMC_DOMAIN_THREAD) {
1007 		imc_global_refc.id = IMC_DOMAIN_THREAD;
1008 		imc_global_refc.refc++;
1009 	} else {
1010 		spin_unlock(&imc_global_refc.lock);
1011 		return -EBUSY;
1012 	}
1013 	spin_unlock(&imc_global_refc.lock);
1014 
1015 	event->pmu->task_ctx_nr = perf_sw_context;
1016 	event->destroy = reset_global_refc;
1017 	return 0;
1018 }
1019 
1020 static bool is_thread_imc_pmu(struct perf_event *event)
1021 {
1022 	if (!strncmp(event->pmu->name, "thread_imc", strlen("thread_imc")))
1023 		return true;
1024 
1025 	return false;
1026 }
1027 
1028 static __be64 *get_event_base_addr(struct perf_event *event)
1029 {
1030 	u64 addr;
1031 
1032 	if (is_thread_imc_pmu(event)) {
1033 		addr = (u64)per_cpu(thread_imc_mem, smp_processor_id());
1034 		return (__be64 *)(addr + (event->attr.config & IMC_EVENT_OFFSET_MASK));
1035 	}
1036 
1037 	return (__be64 *)event->hw.event_base;
1038 }
1039 
1040 static void thread_imc_pmu_start_txn(struct pmu *pmu,
1041 				     unsigned int txn_flags)
1042 {
1043 	if (txn_flags & ~PERF_PMU_TXN_ADD)
1044 		return;
1045 	perf_pmu_disable(pmu);
1046 }
1047 
1048 static void thread_imc_pmu_cancel_txn(struct pmu *pmu)
1049 {
1050 	perf_pmu_enable(pmu);
1051 }
1052 
1053 static int thread_imc_pmu_commit_txn(struct pmu *pmu)
1054 {
1055 	perf_pmu_enable(pmu);
1056 	return 0;
1057 }
1058 
1059 static u64 imc_read_counter(struct perf_event *event)
1060 {
1061 	__be64 *addr;
1062 	u64 data;
1063 
1064 	/*
1065 	 * In-Memory Collection (IMC) counters are free flowing counters.
1066 	 * So we take a snapshot of the counter value on enable and save it
1067 	 * to calculate the delta at later stage to present the event counter
1068 	 * value.
1069 	 */
1070 	addr = get_event_base_addr(event);
1071 	data = be64_to_cpu(READ_ONCE(*addr));
1072 	local64_set(&event->hw.prev_count, data);
1073 
1074 	return data;
1075 }
1076 
1077 static void imc_event_update(struct perf_event *event)
1078 {
1079 	u64 counter_prev, counter_new, final_count;
1080 
1081 	counter_prev = local64_read(&event->hw.prev_count);
1082 	counter_new = imc_read_counter(event);
1083 	final_count = counter_new - counter_prev;
1084 
1085 	/* Update the delta to the event count */
1086 	local64_add(final_count, &event->count);
1087 }
1088 
1089 static void imc_event_start(struct perf_event *event, int flags)
1090 {
1091 	/*
1092 	 * In Memory Counters are free flowing counters. HW or the microcode
1093 	 * keeps adding to the counter offset in memory. To get event
1094 	 * counter value, we snapshot the value here and we calculate
1095 	 * delta at later point.
1096 	 */
1097 	imc_read_counter(event);
1098 }
1099 
1100 static void imc_event_stop(struct perf_event *event, int flags)
1101 {
1102 	/*
1103 	 * Take a snapshot and calculate the delta and update
1104 	 * the event counter values.
1105 	 */
1106 	imc_event_update(event);
1107 }
1108 
1109 static int imc_event_add(struct perf_event *event, int flags)
1110 {
1111 	if (flags & PERF_EF_START)
1112 		imc_event_start(event, flags);
1113 
1114 	return 0;
1115 }
1116 
1117 static int thread_imc_event_add(struct perf_event *event, int flags)
1118 {
1119 	int core_id;
1120 	struct imc_pmu_ref *ref;
1121 	u64 ldbar_value, *local_mem = per_cpu(thread_imc_mem, smp_processor_id());
1122 
1123 	if (flags & PERF_EF_START)
1124 		imc_event_start(event, flags);
1125 
1126 	if (!is_core_imc_mem_inited(smp_processor_id()))
1127 		return -EINVAL;
1128 
1129 	core_id = smp_processor_id() / threads_per_core;
1130 	ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | THREAD_IMC_ENABLE;
1131 	mtspr(SPRN_LDBAR, ldbar_value);
1132 
1133 	/*
1134 	 * imc pmus are enabled only when it is used.
1135 	 * See if this is triggered for the first time.
1136 	 * If yes, take the lock and enable the counters.
1137 	 * If not, just increment the count in ref count struct.
1138 	 */
1139 	ref = &core_imc_refc[core_id];
1140 	if (!ref)
1141 		return -EINVAL;
1142 
1143 	spin_lock(&ref->lock);
1144 	if (ref->refc == 0) {
1145 		if (opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
1146 		    get_hard_smp_processor_id(smp_processor_id()))) {
1147 			spin_unlock(&ref->lock);
1148 			pr_err("thread-imc: Unable to start the counter\
1149 				for core %d\n", core_id);
1150 			return -EINVAL;
1151 		}
1152 	}
1153 	++ref->refc;
1154 	spin_unlock(&ref->lock);
1155 	return 0;
1156 }
1157 
1158 static void thread_imc_event_del(struct perf_event *event, int flags)
1159 {
1160 
1161 	int core_id;
1162 	struct imc_pmu_ref *ref;
1163 
1164 	core_id = smp_processor_id() / threads_per_core;
1165 	ref = &core_imc_refc[core_id];
1166 	if (!ref) {
1167 		pr_debug("imc: Failed to get event reference count\n");
1168 		return;
1169 	}
1170 
1171 	spin_lock(&ref->lock);
1172 	ref->refc--;
1173 	if (ref->refc == 0) {
1174 		if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
1175 		    get_hard_smp_processor_id(smp_processor_id()))) {
1176 			spin_unlock(&ref->lock);
1177 			pr_err("thread-imc: Unable to stop the counters\
1178 				for core %d\n", core_id);
1179 			return;
1180 		}
1181 	} else if (ref->refc < 0) {
1182 		ref->refc = 0;
1183 	}
1184 	spin_unlock(&ref->lock);
1185 
1186 	/* Set bit 0 of LDBAR to zero, to stop posting updates to memory */
1187 	mtspr(SPRN_LDBAR, (mfspr(SPRN_LDBAR) & (~(1UL << 63))));
1188 
1189 	/*
1190 	 * Take a snapshot and calculate the delta and update
1191 	 * the event counter values.
1192 	 */
1193 	imc_event_update(event);
1194 }
1195 
1196 /*
1197  * Allocate a page of memory for each cpu, and load LDBAR with 0.
1198  */
1199 static int trace_imc_mem_alloc(int cpu_id, int size)
1200 {
1201 	u64 *local_mem = per_cpu(trace_imc_mem, cpu_id);
1202 	int phys_id = cpu_to_node(cpu_id), rc = 0;
1203 	int core_id = (cpu_id / threads_per_core);
1204 
1205 	if (!local_mem) {
1206 		struct page *page;
1207 
1208 		page = alloc_pages_node(phys_id,
1209 				GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
1210 				__GFP_NOWARN, get_order(size));
1211 		if (!page)
1212 			return -ENOMEM;
1213 		local_mem = page_address(page);
1214 		per_cpu(trace_imc_mem, cpu_id) = local_mem;
1215 
1216 		/* Initialise the counters for trace mode */
1217 		rc = opal_imc_counters_init(OPAL_IMC_COUNTERS_TRACE, __pa((void *)local_mem),
1218 					    get_hard_smp_processor_id(cpu_id));
1219 		if (rc) {
1220 			pr_info("IMC:opal init failed for trace imc\n");
1221 			return rc;
1222 		}
1223 	}
1224 
1225 	trace_imc_refc[core_id].id = core_id;
1226 	spin_lock_init(&trace_imc_refc[core_id].lock);
1227 
1228 	mtspr(SPRN_LDBAR, 0);
1229 	return 0;
1230 }
1231 
1232 static int ppc_trace_imc_cpu_online(unsigned int cpu)
1233 {
1234 	return trace_imc_mem_alloc(cpu, trace_imc_mem_size);
1235 }
1236 
1237 static int ppc_trace_imc_cpu_offline(unsigned int cpu)
1238 {
1239 	/*
1240 	 * No need to set bit 0 of LDBAR to zero, as
1241 	 * it is set to zero for imc trace-mode
1242 	 *
1243 	 * Reduce the refc if any trace-imc event running
1244 	 * on this cpu.
1245 	 */
1246 	spin_lock(&imc_global_refc.lock);
1247 	if (imc_global_refc.id == IMC_DOMAIN_TRACE)
1248 		imc_global_refc.refc--;
1249 	spin_unlock(&imc_global_refc.lock);
1250 
1251 	return 0;
1252 }
1253 
1254 static int trace_imc_cpu_init(void)
1255 {
1256 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_TRACE_IMC_ONLINE,
1257 			  "perf/powerpc/imc_trace:online",
1258 			  ppc_trace_imc_cpu_online,
1259 			  ppc_trace_imc_cpu_offline);
1260 }
1261 
1262 static u64 get_trace_imc_event_base_addr(void)
1263 {
1264 	return (u64)per_cpu(trace_imc_mem, smp_processor_id());
1265 }
1266 
1267 /*
1268  * Function to parse trace-imc data obtained
1269  * and to prepare the perf sample.
1270  */
1271 static int trace_imc_prepare_sample(struct trace_imc_data *mem,
1272 				    struct perf_sample_data *data,
1273 				    u64 *prev_tb,
1274 				    struct perf_event_header *header,
1275 				    struct perf_event *event)
1276 {
1277 	/* Sanity checks for a valid record */
1278 	if (be64_to_cpu(READ_ONCE(mem->tb1)) > *prev_tb)
1279 		*prev_tb = be64_to_cpu(READ_ONCE(mem->tb1));
1280 	else
1281 		return -EINVAL;
1282 
1283 	if ((be64_to_cpu(READ_ONCE(mem->tb1)) & IMC_TRACE_RECORD_TB1_MASK) !=
1284 			 be64_to_cpu(READ_ONCE(mem->tb2)))
1285 		return -EINVAL;
1286 
1287 	/* Prepare perf sample */
1288 	data->ip =  be64_to_cpu(READ_ONCE(mem->ip));
1289 	data->period = event->hw.last_period;
1290 
1291 	header->type = PERF_RECORD_SAMPLE;
1292 	header->size = sizeof(*header) + event->header_size;
1293 	header->misc = 0;
1294 
1295 	if (cpu_has_feature(CPU_FTR_ARCH_31)) {
1296 		switch (IMC_TRACE_RECORD_VAL_HVPR(be64_to_cpu(READ_ONCE(mem->val)))) {
1297 		case 0:/* when MSR HV and PR not set in the trace-record */
1298 			header->misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1299 			break;
1300 		case 1: /* MSR HV is 0 and PR is 1 */
1301 			header->misc |= PERF_RECORD_MISC_GUEST_USER;
1302 			break;
1303 		case 2: /* MSR HV is 1 and PR is 0 */
1304 			header->misc |= PERF_RECORD_MISC_KERNEL;
1305 			break;
1306 		case 3: /* MSR HV is 1 and PR is 1 */
1307 			header->misc |= PERF_RECORD_MISC_USER;
1308 			break;
1309 		default:
1310 			pr_info("IMC: Unable to set the flag based on MSR bits\n");
1311 			break;
1312 		}
1313 	} else {
1314 		if (is_kernel_addr(data->ip))
1315 			header->misc |= PERF_RECORD_MISC_KERNEL;
1316 		else
1317 			header->misc |= PERF_RECORD_MISC_USER;
1318 	}
1319 	perf_event_header__init_id(header, data, event);
1320 
1321 	return 0;
1322 }
1323 
1324 static void dump_trace_imc_data(struct perf_event *event)
1325 {
1326 	struct trace_imc_data *mem;
1327 	int i, ret;
1328 	u64 prev_tb = 0;
1329 
1330 	mem = (struct trace_imc_data *)get_trace_imc_event_base_addr();
1331 	for (i = 0; i < (trace_imc_mem_size / sizeof(struct trace_imc_data));
1332 		i++, mem++) {
1333 		struct perf_sample_data data;
1334 		struct perf_event_header header;
1335 
1336 		ret = trace_imc_prepare_sample(mem, &data, &prev_tb, &header, event);
1337 		if (ret) /* Exit, if not a valid record */
1338 			break;
1339 		else {
1340 			/* If this is a valid record, create the sample */
1341 			struct perf_output_handle handle;
1342 
1343 			if (perf_output_begin(&handle, &data, event, header.size))
1344 				return;
1345 
1346 			perf_output_sample(&handle, &header, &data, event);
1347 			perf_output_end(&handle);
1348 		}
1349 	}
1350 }
1351 
1352 static int trace_imc_event_add(struct perf_event *event, int flags)
1353 {
1354 	int core_id = smp_processor_id() / threads_per_core;
1355 	struct imc_pmu_ref *ref = NULL;
1356 	u64 local_mem, ldbar_value;
1357 
1358 	/* Set trace-imc bit in ldbar and load ldbar with per-thread memory address */
1359 	local_mem = get_trace_imc_event_base_addr();
1360 	ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | TRACE_IMC_ENABLE;
1361 
1362 	/* trace-imc reference count */
1363 	if (trace_imc_refc)
1364 		ref = &trace_imc_refc[core_id];
1365 	if (!ref) {
1366 		pr_debug("imc: Failed to get the event reference count\n");
1367 		return -EINVAL;
1368 	}
1369 
1370 	mtspr(SPRN_LDBAR, ldbar_value);
1371 	spin_lock(&ref->lock);
1372 	if (ref->refc == 0) {
1373 		if (opal_imc_counters_start(OPAL_IMC_COUNTERS_TRACE,
1374 				get_hard_smp_processor_id(smp_processor_id()))) {
1375 			spin_unlock(&ref->lock);
1376 			pr_err("trace-imc: Unable to start the counters for core %d\n", core_id);
1377 			return -EINVAL;
1378 		}
1379 	}
1380 	++ref->refc;
1381 	spin_unlock(&ref->lock);
1382 	return 0;
1383 }
1384 
1385 static void trace_imc_event_read(struct perf_event *event)
1386 {
1387 	return;
1388 }
1389 
1390 static void trace_imc_event_stop(struct perf_event *event, int flags)
1391 {
1392 	u64 local_mem = get_trace_imc_event_base_addr();
1393 	dump_trace_imc_data(event);
1394 	memset((void *)local_mem, 0, sizeof(u64));
1395 }
1396 
1397 static void trace_imc_event_start(struct perf_event *event, int flags)
1398 {
1399 	return;
1400 }
1401 
1402 static void trace_imc_event_del(struct perf_event *event, int flags)
1403 {
1404 	int core_id = smp_processor_id() / threads_per_core;
1405 	struct imc_pmu_ref *ref = NULL;
1406 
1407 	if (trace_imc_refc)
1408 		ref = &trace_imc_refc[core_id];
1409 	if (!ref) {
1410 		pr_debug("imc: Failed to get event reference count\n");
1411 		return;
1412 	}
1413 
1414 	spin_lock(&ref->lock);
1415 	ref->refc--;
1416 	if (ref->refc == 0) {
1417 		if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_TRACE,
1418 				get_hard_smp_processor_id(smp_processor_id()))) {
1419 			spin_unlock(&ref->lock);
1420 			pr_err("trace-imc: Unable to stop the counters for core %d\n", core_id);
1421 			return;
1422 		}
1423 	} else if (ref->refc < 0) {
1424 		ref->refc = 0;
1425 	}
1426 	spin_unlock(&ref->lock);
1427 
1428 	trace_imc_event_stop(event, flags);
1429 }
1430 
1431 static int trace_imc_event_init(struct perf_event *event)
1432 {
1433 	if (event->attr.type != event->pmu->type)
1434 		return -ENOENT;
1435 
1436 	if (!perfmon_capable())
1437 		return -EACCES;
1438 
1439 	/* Return if this is a couting event */
1440 	if (event->attr.sample_period == 0)
1441 		return -ENOENT;
1442 
1443 	/*
1444 	 * Take the global lock, and make sure
1445 	 * no other thread is running any core/thread imc
1446 	 * events
1447 	 */
1448 	spin_lock(&imc_global_refc.lock);
1449 	if (imc_global_refc.id == 0 || imc_global_refc.id == IMC_DOMAIN_TRACE) {
1450 		/*
1451 		 * No core/thread imc events are running in the
1452 		 * system, so set the refc.id to trace-imc.
1453 		 */
1454 		imc_global_refc.id = IMC_DOMAIN_TRACE;
1455 		imc_global_refc.refc++;
1456 	} else {
1457 		spin_unlock(&imc_global_refc.lock);
1458 		return -EBUSY;
1459 	}
1460 	spin_unlock(&imc_global_refc.lock);
1461 
1462 	event->hw.idx = -1;
1463 
1464 	/*
1465 	 * There can only be a single PMU for perf_hw_context events which is assigned to
1466 	 * core PMU. Hence use "perf_sw_context" for trace_imc.
1467 	 */
1468 	event->pmu->task_ctx_nr = perf_sw_context;
1469 	event->destroy = reset_global_refc;
1470 	return 0;
1471 }
1472 
1473 /* update_pmu_ops : Populate the appropriate operations for "pmu" */
1474 static int update_pmu_ops(struct imc_pmu *pmu)
1475 {
1476 	pmu->pmu.task_ctx_nr = perf_invalid_context;
1477 	pmu->pmu.add = imc_event_add;
1478 	pmu->pmu.del = imc_event_stop;
1479 	pmu->pmu.start = imc_event_start;
1480 	pmu->pmu.stop = imc_event_stop;
1481 	pmu->pmu.read = imc_event_update;
1482 	pmu->pmu.attr_groups = pmu->attr_groups;
1483 	pmu->pmu.capabilities = PERF_PMU_CAP_NO_EXCLUDE;
1484 	pmu->attr_groups[IMC_FORMAT_ATTR] = &imc_format_group;
1485 
1486 	switch (pmu->domain) {
1487 	case IMC_DOMAIN_NEST:
1488 		pmu->pmu.event_init = nest_imc_event_init;
1489 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1490 		break;
1491 	case IMC_DOMAIN_CORE:
1492 		pmu->pmu.event_init = core_imc_event_init;
1493 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1494 		break;
1495 	case IMC_DOMAIN_THREAD:
1496 		pmu->pmu.event_init = thread_imc_event_init;
1497 		pmu->pmu.add = thread_imc_event_add;
1498 		pmu->pmu.del = thread_imc_event_del;
1499 		pmu->pmu.start_txn = thread_imc_pmu_start_txn;
1500 		pmu->pmu.cancel_txn = thread_imc_pmu_cancel_txn;
1501 		pmu->pmu.commit_txn = thread_imc_pmu_commit_txn;
1502 		break;
1503 	case IMC_DOMAIN_TRACE:
1504 		pmu->pmu.event_init = trace_imc_event_init;
1505 		pmu->pmu.add = trace_imc_event_add;
1506 		pmu->pmu.del = trace_imc_event_del;
1507 		pmu->pmu.start = trace_imc_event_start;
1508 		pmu->pmu.stop = trace_imc_event_stop;
1509 		pmu->pmu.read = trace_imc_event_read;
1510 		pmu->attr_groups[IMC_FORMAT_ATTR] = &trace_imc_format_group;
1511 		break;
1512 	default:
1513 		break;
1514 	}
1515 
1516 	return 0;
1517 }
1518 
1519 /* init_nest_pmu_ref: Initialize the imc_pmu_ref struct for all the nodes */
1520 static int init_nest_pmu_ref(void)
1521 {
1522 	int nid, i, cpu;
1523 
1524 	nest_imc_refc = kcalloc(num_possible_nodes(), sizeof(*nest_imc_refc),
1525 								GFP_KERNEL);
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 = kcalloc(get_max_nest_dev() + 1,
1697 						sizeof(struct imc_pmu *),
1698 						GFP_KERNEL);
1699 			if (!per_nest_pmu_arr)
1700 				goto err;
1701 		}
1702 		per_nest_pmu_arr[pmu_index] = pmu_ptr;
1703 		break;
1704 	case IMC_DOMAIN_CORE:
1705 		/* Update the pmu name */
1706 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1707 		if (!pmu_ptr->pmu.name)
1708 			goto err;
1709 
1710 		nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1711 		pmu_ptr->mem_info = kcalloc(nr_cores, sizeof(struct imc_mem_info),
1712 								GFP_KERNEL);
1713 
1714 		if (!pmu_ptr->mem_info)
1715 			goto err;
1716 
1717 		core_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1718 								GFP_KERNEL);
1719 
1720 		if (!core_imc_refc) {
1721 			kfree(pmu_ptr->mem_info);
1722 			goto err;
1723 		}
1724 
1725 		core_imc_pmu = pmu_ptr;
1726 		break;
1727 	case IMC_DOMAIN_THREAD:
1728 		/* Update the pmu name */
1729 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1730 		if (!pmu_ptr->pmu.name)
1731 			goto err;
1732 
1733 		thread_imc_mem_size = pmu_ptr->counter_mem_size;
1734 		for_each_online_cpu(cpu) {
1735 			res = thread_imc_mem_alloc(cpu, pmu_ptr->counter_mem_size);
1736 			if (res) {
1737 				cleanup_all_thread_imc_memory();
1738 				goto err;
1739 			}
1740 		}
1741 
1742 		thread_imc_pmu = pmu_ptr;
1743 		break;
1744 	case IMC_DOMAIN_TRACE:
1745 		/* Update the pmu name */
1746 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1747 		if (!pmu_ptr->pmu.name)
1748 			return -ENOMEM;
1749 
1750 		nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1751 		trace_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1752 								GFP_KERNEL);
1753 		if (!trace_imc_refc)
1754 			return -ENOMEM;
1755 
1756 		trace_imc_mem_size = pmu_ptr->counter_mem_size;
1757 		for_each_online_cpu(cpu) {
1758 			res = trace_imc_mem_alloc(cpu, trace_imc_mem_size);
1759 			if (res) {
1760 				cleanup_all_trace_imc_memory();
1761 				goto err;
1762 			}
1763 		}
1764 		break;
1765 	default:
1766 		return -EINVAL;
1767 	}
1768 
1769 	return 0;
1770 err:
1771 	return res;
1772 }
1773 
1774 /*
1775  * init_imc_pmu : Setup and register the IMC pmu device.
1776  *
1777  * @parent:	Device tree unit node
1778  * @pmu_ptr:	memory allocated for this pmu
1779  * @pmu_idx:	Count of nest pmc registered
1780  *
1781  * init_imc_pmu() setup pmu cpumask and registers for a cpu hotplug callback.
1782  * Handles failure cases and accordingly frees memory.
1783  */
1784 int init_imc_pmu(struct device_node *parent, struct imc_pmu *pmu_ptr, int pmu_idx)
1785 {
1786 	int ret;
1787 
1788 	ret = imc_mem_init(pmu_ptr, parent, pmu_idx);
1789 	if (ret)
1790 		goto err_free_mem;
1791 
1792 	switch (pmu_ptr->domain) {
1793 	case IMC_DOMAIN_NEST:
1794 		/*
1795 		* Nest imc pmu need only one cpu per chip, we initialize the
1796 		* cpumask for the first nest imc pmu and use the same for the
1797 		* rest. To handle the cpuhotplug callback unregister, we track
1798 		* the number of nest pmus in "nest_pmus".
1799 		*/
1800 		mutex_lock(&nest_init_lock);
1801 		if (nest_pmus == 0) {
1802 			ret = init_nest_pmu_ref();
1803 			if (ret) {
1804 				mutex_unlock(&nest_init_lock);
1805 				kfree(per_nest_pmu_arr);
1806 				per_nest_pmu_arr = NULL;
1807 				goto err_free_mem;
1808 			}
1809 			/* Register for cpu hotplug notification. */
1810 			ret = nest_pmu_cpumask_init();
1811 			if (ret) {
1812 				mutex_unlock(&nest_init_lock);
1813 				kfree(nest_imc_refc);
1814 				kfree(per_nest_pmu_arr);
1815 				per_nest_pmu_arr = NULL;
1816 				goto err_free_mem;
1817 			}
1818 		}
1819 		nest_pmus++;
1820 		mutex_unlock(&nest_init_lock);
1821 		break;
1822 	case IMC_DOMAIN_CORE:
1823 		ret = core_imc_pmu_cpumask_init();
1824 		if (ret) {
1825 			cleanup_all_core_imc_memory();
1826 			goto err_free_mem;
1827 		}
1828 
1829 		break;
1830 	case IMC_DOMAIN_THREAD:
1831 		ret = thread_imc_cpu_init();
1832 		if (ret) {
1833 			cleanup_all_thread_imc_memory();
1834 			goto err_free_mem;
1835 		}
1836 
1837 		break;
1838 	case IMC_DOMAIN_TRACE:
1839 		ret = trace_imc_cpu_init();
1840 		if (ret) {
1841 			cleanup_all_trace_imc_memory();
1842 			goto err_free_mem;
1843 		}
1844 
1845 		break;
1846 	default:
1847 		return  -EINVAL;	/* Unknown domain */
1848 	}
1849 
1850 	ret = update_events_in_group(parent, pmu_ptr);
1851 	if (ret)
1852 		goto err_free_cpuhp_mem;
1853 
1854 	ret = update_pmu_ops(pmu_ptr);
1855 	if (ret)
1856 		goto err_free_cpuhp_mem;
1857 
1858 	ret = perf_pmu_register(&pmu_ptr->pmu, pmu_ptr->pmu.name, -1);
1859 	if (ret)
1860 		goto err_free_cpuhp_mem;
1861 
1862 	pr_debug("%s performance monitor hardware support registered\n",
1863 							pmu_ptr->pmu.name);
1864 
1865 	return 0;
1866 
1867 err_free_cpuhp_mem:
1868 	imc_common_cpuhp_mem_free(pmu_ptr);
1869 err_free_mem:
1870 	imc_common_mem_free(pmu_ptr);
1871 	return ret;
1872 }
1873