xref: /linux/arch/powerpc/perf/imc-pmu.c (revision b9d1fdc6f4ac1b6e49f9deafaf137da1407d9af1)
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 	u16 misc = 0;
1279 
1280 	/* Sanity checks for a valid record */
1281 	if (be64_to_cpu(READ_ONCE(mem->tb1)) > *prev_tb)
1282 		*prev_tb = be64_to_cpu(READ_ONCE(mem->tb1));
1283 	else
1284 		return -EINVAL;
1285 
1286 	if ((be64_to_cpu(READ_ONCE(mem->tb1)) & IMC_TRACE_RECORD_TB1_MASK) !=
1287 			 be64_to_cpu(READ_ONCE(mem->tb2)))
1288 		return -EINVAL;
1289 
1290 	/* Prepare perf sample */
1291 	data->ip =  be64_to_cpu(READ_ONCE(mem->ip));
1292 	data->period = event->hw.last_period;
1293 
1294 	if (cpu_has_feature(CPU_FTR_ARCH_31)) {
1295 		switch (IMC_TRACE_RECORD_VAL_HVPR(be64_to_cpu(READ_ONCE(mem->val)))) {
1296 		case 0:/* when MSR HV and PR not set in the trace-record */
1297 			misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1298 			break;
1299 		case 1: /* MSR HV is 0 and PR is 1 */
1300 			misc |= PERF_RECORD_MISC_GUEST_USER;
1301 			break;
1302 		case 2: /* MSR HV is 1 and PR is 0 */
1303 			misc |= PERF_RECORD_MISC_KERNEL;
1304 			break;
1305 		case 3: /* MSR HV is 1 and PR is 1 */
1306 			misc |= PERF_RECORD_MISC_USER;
1307 			break;
1308 		default:
1309 			pr_info("IMC: Unable to set the flag based on MSR bits\n");
1310 			break;
1311 		}
1312 	} else {
1313 		if (is_kernel_addr(data->ip))
1314 			misc |= PERF_RECORD_MISC_KERNEL;
1315 		else
1316 			misc |= PERF_RECORD_MISC_USER;
1317 	}
1318 	perf_event_header__init(header, data,
1319 				PERF_RECORD_SAMPLE, misc,
1320 				sizeof(*header) + event->header_size,
1321 				event);
1322 
1323 	return 0;
1324 }
1325 
1326 static void dump_trace_imc_data(struct perf_event *event)
1327 {
1328 	struct trace_imc_data *mem;
1329 	int i, ret;
1330 	u64 prev_tb = 0;
1331 
1332 	mem = (struct trace_imc_data *)get_trace_imc_event_base_addr();
1333 	for (i = 0; i < (trace_imc_mem_size / sizeof(struct trace_imc_data));
1334 		i++, mem++) {
1335 		struct perf_sample_data data;
1336 		struct perf_event_header header;
1337 
1338 		ret = trace_imc_prepare_sample(mem, &data, &prev_tb, &header, event);
1339 		if (ret) /* Exit, if not a valid record */
1340 			break;
1341 		else {
1342 			/* If this is a valid record, create the sample */
1343 			struct perf_output_handle handle;
1344 
1345 			if (perf_output_begin(&handle, &data, event, header.size))
1346 				return;
1347 
1348 			perf_output_sample(&handle, &header, &data, event);
1349 			perf_output_end(&handle);
1350 		}
1351 	}
1352 }
1353 
1354 static int trace_imc_event_add(struct perf_event *event, int flags)
1355 {
1356 	int core_id = smp_processor_id() / threads_per_core;
1357 	struct imc_pmu_ref *ref = NULL;
1358 	u64 local_mem, ldbar_value;
1359 
1360 	/* Set trace-imc bit in ldbar and load ldbar with per-thread memory address */
1361 	local_mem = get_trace_imc_event_base_addr();
1362 	ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | TRACE_IMC_ENABLE;
1363 
1364 	/* trace-imc reference count */
1365 	if (trace_imc_refc)
1366 		ref = &trace_imc_refc[core_id];
1367 	if (!ref) {
1368 		pr_debug("imc: Failed to get the event reference count\n");
1369 		return -EINVAL;
1370 	}
1371 
1372 	mtspr(SPRN_LDBAR, ldbar_value);
1373 	spin_lock(&ref->lock);
1374 	if (ref->refc == 0) {
1375 		if (opal_imc_counters_start(OPAL_IMC_COUNTERS_TRACE,
1376 				get_hard_smp_processor_id(smp_processor_id()))) {
1377 			spin_unlock(&ref->lock);
1378 			pr_err("trace-imc: Unable to start the counters for core %d\n", core_id);
1379 			return -EINVAL;
1380 		}
1381 	}
1382 	++ref->refc;
1383 	spin_unlock(&ref->lock);
1384 	return 0;
1385 }
1386 
1387 static void trace_imc_event_read(struct perf_event *event)
1388 {
1389 	return;
1390 }
1391 
1392 static void trace_imc_event_stop(struct perf_event *event, int flags)
1393 {
1394 	u64 local_mem = get_trace_imc_event_base_addr();
1395 	dump_trace_imc_data(event);
1396 	memset((void *)local_mem, 0, sizeof(u64));
1397 }
1398 
1399 static void trace_imc_event_start(struct perf_event *event, int flags)
1400 {
1401 	return;
1402 }
1403 
1404 static void trace_imc_event_del(struct perf_event *event, int flags)
1405 {
1406 	int core_id = smp_processor_id() / threads_per_core;
1407 	struct imc_pmu_ref *ref = NULL;
1408 
1409 	if (trace_imc_refc)
1410 		ref = &trace_imc_refc[core_id];
1411 	if (!ref) {
1412 		pr_debug("imc: Failed to get event reference count\n");
1413 		return;
1414 	}
1415 
1416 	spin_lock(&ref->lock);
1417 	ref->refc--;
1418 	if (ref->refc == 0) {
1419 		if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_TRACE,
1420 				get_hard_smp_processor_id(smp_processor_id()))) {
1421 			spin_unlock(&ref->lock);
1422 			pr_err("trace-imc: Unable to stop the counters for core %d\n", core_id);
1423 			return;
1424 		}
1425 	} else if (ref->refc < 0) {
1426 		ref->refc = 0;
1427 	}
1428 	spin_unlock(&ref->lock);
1429 
1430 	trace_imc_event_stop(event, flags);
1431 }
1432 
1433 static int trace_imc_event_init(struct perf_event *event)
1434 {
1435 	if (event->attr.type != event->pmu->type)
1436 		return -ENOENT;
1437 
1438 	if (!perfmon_capable())
1439 		return -EACCES;
1440 
1441 	/* Return if this is a couting event */
1442 	if (event->attr.sample_period == 0)
1443 		return -ENOENT;
1444 
1445 	/*
1446 	 * Take the global lock, and make sure
1447 	 * no other thread is running any core/thread imc
1448 	 * events
1449 	 */
1450 	spin_lock(&imc_global_refc.lock);
1451 	if (imc_global_refc.id == 0 || imc_global_refc.id == IMC_DOMAIN_TRACE) {
1452 		/*
1453 		 * No core/thread imc events are running in the
1454 		 * system, so set the refc.id to trace-imc.
1455 		 */
1456 		imc_global_refc.id = IMC_DOMAIN_TRACE;
1457 		imc_global_refc.refc++;
1458 	} else {
1459 		spin_unlock(&imc_global_refc.lock);
1460 		return -EBUSY;
1461 	}
1462 	spin_unlock(&imc_global_refc.lock);
1463 
1464 	event->hw.idx = -1;
1465 
1466 	/*
1467 	 * There can only be a single PMU for perf_hw_context events which is assigned to
1468 	 * core PMU. Hence use "perf_sw_context" for trace_imc.
1469 	 */
1470 	event->pmu->task_ctx_nr = perf_sw_context;
1471 	event->destroy = reset_global_refc;
1472 	return 0;
1473 }
1474 
1475 /* update_pmu_ops : Populate the appropriate operations for "pmu" */
1476 static int update_pmu_ops(struct imc_pmu *pmu)
1477 {
1478 	pmu->pmu.task_ctx_nr = perf_invalid_context;
1479 	pmu->pmu.add = imc_event_add;
1480 	pmu->pmu.del = imc_event_stop;
1481 	pmu->pmu.start = imc_event_start;
1482 	pmu->pmu.stop = imc_event_stop;
1483 	pmu->pmu.read = imc_event_update;
1484 	pmu->pmu.attr_groups = pmu->attr_groups;
1485 	pmu->pmu.capabilities = PERF_PMU_CAP_NO_EXCLUDE;
1486 	pmu->attr_groups[IMC_FORMAT_ATTR] = &imc_format_group;
1487 
1488 	switch (pmu->domain) {
1489 	case IMC_DOMAIN_NEST:
1490 		pmu->pmu.event_init = nest_imc_event_init;
1491 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1492 		break;
1493 	case IMC_DOMAIN_CORE:
1494 		pmu->pmu.event_init = core_imc_event_init;
1495 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1496 		break;
1497 	case IMC_DOMAIN_THREAD:
1498 		pmu->pmu.event_init = thread_imc_event_init;
1499 		pmu->pmu.add = thread_imc_event_add;
1500 		pmu->pmu.del = thread_imc_event_del;
1501 		pmu->pmu.start_txn = thread_imc_pmu_start_txn;
1502 		pmu->pmu.cancel_txn = thread_imc_pmu_cancel_txn;
1503 		pmu->pmu.commit_txn = thread_imc_pmu_commit_txn;
1504 		break;
1505 	case IMC_DOMAIN_TRACE:
1506 		pmu->pmu.event_init = trace_imc_event_init;
1507 		pmu->pmu.add = trace_imc_event_add;
1508 		pmu->pmu.del = trace_imc_event_del;
1509 		pmu->pmu.start = trace_imc_event_start;
1510 		pmu->pmu.stop = trace_imc_event_stop;
1511 		pmu->pmu.read = trace_imc_event_read;
1512 		pmu->attr_groups[IMC_FORMAT_ATTR] = &trace_imc_format_group;
1513 		break;
1514 	default:
1515 		break;
1516 	}
1517 
1518 	return 0;
1519 }
1520 
1521 /* init_nest_pmu_ref: Initialize the imc_pmu_ref struct for all the nodes */
1522 static int init_nest_pmu_ref(void)
1523 {
1524 	int nid, i, cpu;
1525 
1526 	nest_imc_refc = kzalloc_objs(*nest_imc_refc, num_possible_nodes());
1527 
1528 	if (!nest_imc_refc)
1529 		return -ENOMEM;
1530 
1531 	i = 0;
1532 	for_each_node(nid) {
1533 		/*
1534 		 * Take the lock to avoid races while tracking the number of
1535 		 * sessions using the chip's nest pmu units.
1536 		 */
1537 		spin_lock_init(&nest_imc_refc[i].lock);
1538 
1539 		/*
1540 		 * Loop to init the "id" with the node_id. Variable "i" initialized to
1541 		 * 0 and will be used as index to the array. "i" will not go off the
1542 		 * end of the array since the "for_each_node" loops for "N_POSSIBLE"
1543 		 * nodes only.
1544 		 */
1545 		nest_imc_refc[i++].id = nid;
1546 	}
1547 
1548 	/*
1549 	 * Loop to init the per_cpu "local_nest_imc_refc" with the proper
1550 	 * "nest_imc_refc" index. This makes get_nest_pmu_ref() alot simple.
1551 	 */
1552 	for_each_possible_cpu(cpu) {
1553 		nid = cpu_to_node(cpu);
1554 		for (i = 0; i < num_possible_nodes(); i++) {
1555 			if (nest_imc_refc[i].id == nid) {
1556 				per_cpu(local_nest_imc_refc, cpu) = &nest_imc_refc[i];
1557 				break;
1558 			}
1559 		}
1560 	}
1561 	return 0;
1562 }
1563 
1564 static void cleanup_all_core_imc_memory(void)
1565 {
1566 	int i, nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1567 	struct imc_mem_info *ptr = core_imc_pmu->mem_info;
1568 	int size = core_imc_pmu->counter_mem_size;
1569 
1570 	/* mem_info will never be NULL */
1571 	for (i = 0; i < nr_cores; i++) {
1572 		if (ptr[i].vbase)
1573 			free_pages((u64)ptr[i].vbase, get_order(size));
1574 	}
1575 
1576 	kfree(ptr);
1577 	kfree(core_imc_refc);
1578 }
1579 
1580 static void thread_imc_ldbar_disable(void *dummy)
1581 {
1582 	/*
1583 	 * By setting 0th bit of LDBAR to zero, we disable thread-imc
1584 	 * updates to memory.
1585 	 */
1586 	mtspr(SPRN_LDBAR, (mfspr(SPRN_LDBAR) & (~(1UL << 63))));
1587 }
1588 
1589 void thread_imc_disable(void)
1590 {
1591 	on_each_cpu(thread_imc_ldbar_disable, NULL, 1);
1592 }
1593 
1594 static void cleanup_all_thread_imc_memory(void)
1595 {
1596 	int i, order = get_order(thread_imc_mem_size);
1597 
1598 	for_each_online_cpu(i) {
1599 		if (per_cpu(thread_imc_mem, i))
1600 			free_pages((u64)per_cpu(thread_imc_mem, i), order);
1601 
1602 	}
1603 }
1604 
1605 static void cleanup_all_trace_imc_memory(void)
1606 {
1607 	int i, order = get_order(trace_imc_mem_size);
1608 
1609 	for_each_online_cpu(i) {
1610 		if (per_cpu(trace_imc_mem, i))
1611 			free_pages((u64)per_cpu(trace_imc_mem, i), order);
1612 
1613 	}
1614 	kfree(trace_imc_refc);
1615 }
1616 
1617 /* Function to free the attr_groups which are dynamically allocated */
1618 static void imc_common_mem_free(struct imc_pmu *pmu_ptr)
1619 {
1620 	if (pmu_ptr->attr_groups[IMC_EVENT_ATTR])
1621 		kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]->attrs);
1622 	kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]);
1623 }
1624 
1625 /*
1626  * Common function to unregister cpu hotplug callback and
1627  * free the memory.
1628  * TODO: Need to handle pmu unregistering, which will be
1629  * done in followup series.
1630  */
1631 static void imc_common_cpuhp_mem_free(struct imc_pmu *pmu_ptr)
1632 {
1633 	if (pmu_ptr->domain == IMC_DOMAIN_NEST) {
1634 		mutex_lock(&nest_init_lock);
1635 		if (nest_pmus == 1) {
1636 			cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE);
1637 			kfree(nest_imc_refc);
1638 			kfree(per_nest_pmu_arr);
1639 			per_nest_pmu_arr = NULL;
1640 		}
1641 
1642 		if (nest_pmus > 0)
1643 			nest_pmus--;
1644 		mutex_unlock(&nest_init_lock);
1645 	}
1646 
1647 	/* Free core_imc memory */
1648 	if (pmu_ptr->domain == IMC_DOMAIN_CORE) {
1649 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE);
1650 		cleanup_all_core_imc_memory();
1651 	}
1652 
1653 	/* Free thread_imc memory */
1654 	if (pmu_ptr->domain == IMC_DOMAIN_THREAD) {
1655 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE);
1656 		cleanup_all_thread_imc_memory();
1657 	}
1658 
1659 	if (pmu_ptr->domain == IMC_DOMAIN_TRACE) {
1660 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_TRACE_IMC_ONLINE);
1661 		cleanup_all_trace_imc_memory();
1662 	}
1663 }
1664 
1665 /*
1666  * Function to unregister thread-imc if core-imc
1667  * is not registered.
1668  */
1669 void unregister_thread_imc(void)
1670 {
1671 	imc_common_cpuhp_mem_free(thread_imc_pmu);
1672 	imc_common_mem_free(thread_imc_pmu);
1673 	perf_pmu_unregister(&thread_imc_pmu->pmu);
1674 }
1675 
1676 /*
1677  * imc_mem_init : Function to support memory allocation for core imc.
1678  */
1679 static int imc_mem_init(struct imc_pmu *pmu_ptr, struct device_node *parent,
1680 								int pmu_index)
1681 {
1682 	const char *s;
1683 	int nr_cores, cpu, res = -ENOMEM;
1684 
1685 	if (of_property_read_string(parent, "name", &s))
1686 		return -ENODEV;
1687 
1688 	switch (pmu_ptr->domain) {
1689 	case IMC_DOMAIN_NEST:
1690 		/* Update the pmu name */
1691 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s_imc", "nest_", s);
1692 		if (!pmu_ptr->pmu.name)
1693 			goto err;
1694 
1695 		/* Needed for hotplug/migration */
1696 		if (!per_nest_pmu_arr) {
1697 			per_nest_pmu_arr = kzalloc_objs(struct imc_pmu *,
1698 							get_max_nest_dev() + 1);
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 = kzalloc_objs(struct imc_mem_info, nr_cores);
1712 
1713 		if (!pmu_ptr->mem_info)
1714 			goto err;
1715 
1716 		core_imc_refc = kzalloc_objs(struct imc_pmu_ref, nr_cores);
1717 
1718 		if (!core_imc_refc) {
1719 			kfree(pmu_ptr->mem_info);
1720 			goto err;
1721 		}
1722 
1723 		core_imc_pmu = pmu_ptr;
1724 		break;
1725 	case IMC_DOMAIN_THREAD:
1726 		/* Update the pmu name */
1727 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1728 		if (!pmu_ptr->pmu.name)
1729 			goto err;
1730 
1731 		thread_imc_mem_size = pmu_ptr->counter_mem_size;
1732 		for_each_online_cpu(cpu) {
1733 			res = thread_imc_mem_alloc(cpu, pmu_ptr->counter_mem_size);
1734 			if (res) {
1735 				cleanup_all_thread_imc_memory();
1736 				goto err;
1737 			}
1738 		}
1739 
1740 		thread_imc_pmu = pmu_ptr;
1741 		break;
1742 	case IMC_DOMAIN_TRACE:
1743 		/* Update the pmu name */
1744 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1745 		if (!pmu_ptr->pmu.name)
1746 			return -ENOMEM;
1747 
1748 		nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1749 		trace_imc_refc = kzalloc_objs(struct imc_pmu_ref, nr_cores);
1750 		if (!trace_imc_refc)
1751 			return -ENOMEM;
1752 
1753 		trace_imc_mem_size = pmu_ptr->counter_mem_size;
1754 		for_each_online_cpu(cpu) {
1755 			res = trace_imc_mem_alloc(cpu, trace_imc_mem_size);
1756 			if (res) {
1757 				cleanup_all_trace_imc_memory();
1758 				goto err;
1759 			}
1760 		}
1761 		break;
1762 	default:
1763 		return -EINVAL;
1764 	}
1765 
1766 	return 0;
1767 err:
1768 	return res;
1769 }
1770 
1771 /*
1772  * init_imc_pmu : Setup and register the IMC pmu device.
1773  *
1774  * @parent:	Device tree unit node
1775  * @pmu_ptr:	memory allocated for this pmu
1776  * @pmu_idx:	Count of nest pmc registered
1777  *
1778  * init_imc_pmu() setup pmu cpumask and registers for a cpu hotplug callback.
1779  * Handles failure cases and accordingly frees memory.
1780  */
1781 int init_imc_pmu(struct device_node *parent, struct imc_pmu *pmu_ptr, int pmu_idx)
1782 {
1783 	int ret;
1784 
1785 	ret = imc_mem_init(pmu_ptr, parent, pmu_idx);
1786 	if (ret)
1787 		goto err_free_mem;
1788 
1789 	switch (pmu_ptr->domain) {
1790 	case IMC_DOMAIN_NEST:
1791 		/*
1792 		* Nest imc pmu need only one cpu per chip, we initialize the
1793 		* cpumask for the first nest imc pmu and use the same for the
1794 		* rest. To handle the cpuhotplug callback unregister, we track
1795 		* the number of nest pmus in "nest_pmus".
1796 		*/
1797 		mutex_lock(&nest_init_lock);
1798 		if (nest_pmus == 0) {
1799 			ret = init_nest_pmu_ref();
1800 			if (ret) {
1801 				mutex_unlock(&nest_init_lock);
1802 				kfree(per_nest_pmu_arr);
1803 				per_nest_pmu_arr = NULL;
1804 				goto err_free_mem;
1805 			}
1806 			/* Register for cpu hotplug notification. */
1807 			ret = nest_pmu_cpumask_init();
1808 			if (ret) {
1809 				mutex_unlock(&nest_init_lock);
1810 				kfree(nest_imc_refc);
1811 				kfree(per_nest_pmu_arr);
1812 				per_nest_pmu_arr = NULL;
1813 				goto err_free_mem;
1814 			}
1815 		}
1816 		nest_pmus++;
1817 		mutex_unlock(&nest_init_lock);
1818 		break;
1819 	case IMC_DOMAIN_CORE:
1820 		ret = core_imc_pmu_cpumask_init();
1821 		if (ret) {
1822 			cleanup_all_core_imc_memory();
1823 			goto err_free_mem;
1824 		}
1825 
1826 		break;
1827 	case IMC_DOMAIN_THREAD:
1828 		ret = thread_imc_cpu_init();
1829 		if (ret) {
1830 			cleanup_all_thread_imc_memory();
1831 			goto err_free_mem;
1832 		}
1833 
1834 		break;
1835 	case IMC_DOMAIN_TRACE:
1836 		ret = trace_imc_cpu_init();
1837 		if (ret) {
1838 			cleanup_all_trace_imc_memory();
1839 			goto err_free_mem;
1840 		}
1841 
1842 		break;
1843 	default:
1844 		return  -EINVAL;	/* Unknown domain */
1845 	}
1846 
1847 	ret = update_events_in_group(parent, pmu_ptr);
1848 	if (ret)
1849 		goto err_free_cpuhp_mem;
1850 
1851 	ret = update_pmu_ops(pmu_ptr);
1852 	if (ret)
1853 		goto err_free_cpuhp_mem;
1854 
1855 	ret = perf_pmu_register(&pmu_ptr->pmu, pmu_ptr->pmu.name, -1);
1856 	if (ret)
1857 		goto err_free_cpuhp_mem;
1858 
1859 	pr_debug("%s performance monitor hardware support registered\n",
1860 							pmu_ptr->pmu.name);
1861 
1862 	return 0;
1863 
1864 err_free_cpuhp_mem:
1865 	imc_common_cpuhp_mem_free(pmu_ptr);
1866 err_free_mem:
1867 	imc_common_mem_free(pmu_ptr);
1868 	return ret;
1869 }
1870