xref: /openbmc/linux/arch/powerpc/perf/imc-pmu.c (revision 71de0a05)
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_INITIALIZER(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 != 0);
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 u64 * 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 (u64 *)(addr + (event->attr.config & IMC_EVENT_OFFSET_MASK));
1035 	}
1036 
1037 	return (u64 *)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 	u64 *addr, data;
1062 
1063 	/*
1064 	 * In-Memory Collection (IMC) counters are free flowing counters.
1065 	 * So we take a snapshot of the counter value on enable and save it
1066 	 * to calculate the delta at later stage to present the event counter
1067 	 * value.
1068 	 */
1069 	addr = get_event_base_addr(event);
1070 	data = be64_to_cpu(READ_ONCE(*addr));
1071 	local64_set(&event->hw.prev_count, data);
1072 
1073 	return data;
1074 }
1075 
1076 static void imc_event_update(struct perf_event *event)
1077 {
1078 	u64 counter_prev, counter_new, final_count;
1079 
1080 	counter_prev = local64_read(&event->hw.prev_count);
1081 	counter_new = imc_read_counter(event);
1082 	final_count = counter_new - counter_prev;
1083 
1084 	/* Update the delta to the event count */
1085 	local64_add(final_count, &event->count);
1086 }
1087 
1088 static void imc_event_start(struct perf_event *event, int flags)
1089 {
1090 	/*
1091 	 * In Memory Counters are free flowing counters. HW or the microcode
1092 	 * keeps adding to the counter offset in memory. To get event
1093 	 * counter value, we snapshot the value here and we calculate
1094 	 * delta at later point.
1095 	 */
1096 	imc_read_counter(event);
1097 }
1098 
1099 static void imc_event_stop(struct perf_event *event, int flags)
1100 {
1101 	/*
1102 	 * Take a snapshot and calculate the delta and update
1103 	 * the event counter values.
1104 	 */
1105 	imc_event_update(event);
1106 }
1107 
1108 static int imc_event_add(struct perf_event *event, int flags)
1109 {
1110 	if (flags & PERF_EF_START)
1111 		imc_event_start(event, flags);
1112 
1113 	return 0;
1114 }
1115 
1116 static int thread_imc_event_add(struct perf_event *event, int flags)
1117 {
1118 	int core_id;
1119 	struct imc_pmu_ref *ref;
1120 	u64 ldbar_value, *local_mem = per_cpu(thread_imc_mem, smp_processor_id());
1121 
1122 	if (flags & PERF_EF_START)
1123 		imc_event_start(event, flags);
1124 
1125 	if (!is_core_imc_mem_inited(smp_processor_id()))
1126 		return -EINVAL;
1127 
1128 	core_id = smp_processor_id() / threads_per_core;
1129 	ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | THREAD_IMC_ENABLE;
1130 	mtspr(SPRN_LDBAR, ldbar_value);
1131 
1132 	/*
1133 	 * imc pmus are enabled only when it is used.
1134 	 * See if this is triggered for the first time.
1135 	 * If yes, take the lock and enable the counters.
1136 	 * If not, just increment the count in ref count struct.
1137 	 */
1138 	ref = &core_imc_refc[core_id];
1139 	if (!ref)
1140 		return -EINVAL;
1141 
1142 	spin_lock(&ref->lock);
1143 	if (ref->refc == 0) {
1144 		if (opal_imc_counters_start(OPAL_IMC_COUNTERS_CORE,
1145 		    get_hard_smp_processor_id(smp_processor_id()))) {
1146 			spin_unlock(&ref->lock);
1147 			pr_err("thread-imc: Unable to start the counter\
1148 				for core %d\n", core_id);
1149 			return -EINVAL;
1150 		}
1151 	}
1152 	++ref->refc;
1153 	spin_unlock(&ref->lock);
1154 	return 0;
1155 }
1156 
1157 static void thread_imc_event_del(struct perf_event *event, int flags)
1158 {
1159 
1160 	int core_id;
1161 	struct imc_pmu_ref *ref;
1162 
1163 	core_id = smp_processor_id() / threads_per_core;
1164 	ref = &core_imc_refc[core_id];
1165 	if (!ref) {
1166 		pr_debug("imc: Failed to get event reference count\n");
1167 		return;
1168 	}
1169 
1170 	spin_lock(&ref->lock);
1171 	ref->refc--;
1172 	if (ref->refc == 0) {
1173 		if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_CORE,
1174 		    get_hard_smp_processor_id(smp_processor_id()))) {
1175 			spin_unlock(&ref->lock);
1176 			pr_err("thread-imc: Unable to stop the counters\
1177 				for core %d\n", core_id);
1178 			return;
1179 		}
1180 	} else if (ref->refc < 0) {
1181 		ref->refc = 0;
1182 	}
1183 	spin_unlock(&ref->lock);
1184 
1185 	/* Set bit 0 of LDBAR to zero, to stop posting updates to memory */
1186 	mtspr(SPRN_LDBAR, (mfspr(SPRN_LDBAR) & (~(1UL << 63))));
1187 
1188 	/*
1189 	 * Take a snapshot and calculate the delta and update
1190 	 * the event counter values.
1191 	 */
1192 	imc_event_update(event);
1193 }
1194 
1195 /*
1196  * Allocate a page of memory for each cpu, and load LDBAR with 0.
1197  */
1198 static int trace_imc_mem_alloc(int cpu_id, int size)
1199 {
1200 	u64 *local_mem = per_cpu(trace_imc_mem, cpu_id);
1201 	int phys_id = cpu_to_node(cpu_id), rc = 0;
1202 	int core_id = (cpu_id / threads_per_core);
1203 
1204 	if (!local_mem) {
1205 		struct page *page;
1206 
1207 		page = alloc_pages_node(phys_id,
1208 				GFP_KERNEL | __GFP_ZERO | __GFP_THISNODE |
1209 				__GFP_NOWARN, get_order(size));
1210 		if (!page)
1211 			return -ENOMEM;
1212 		local_mem = page_address(page);
1213 		per_cpu(trace_imc_mem, cpu_id) = local_mem;
1214 
1215 		/* Initialise the counters for trace mode */
1216 		rc = opal_imc_counters_init(OPAL_IMC_COUNTERS_TRACE, __pa((void *)local_mem),
1217 					    get_hard_smp_processor_id(cpu_id));
1218 		if (rc) {
1219 			pr_info("IMC:opal init failed for trace imc\n");
1220 			return rc;
1221 		}
1222 	}
1223 
1224 	trace_imc_refc[core_id].id = core_id;
1225 	spin_lock_init(&trace_imc_refc[core_id].lock);
1226 
1227 	mtspr(SPRN_LDBAR, 0);
1228 	return 0;
1229 }
1230 
1231 static int ppc_trace_imc_cpu_online(unsigned int cpu)
1232 {
1233 	return trace_imc_mem_alloc(cpu, trace_imc_mem_size);
1234 }
1235 
1236 static int ppc_trace_imc_cpu_offline(unsigned int cpu)
1237 {
1238 	/*
1239 	 * No need to set bit 0 of LDBAR to zero, as
1240 	 * it is set to zero for imc trace-mode
1241 	 *
1242 	 * Reduce the refc if any trace-imc event running
1243 	 * on this cpu.
1244 	 */
1245 	spin_lock(&imc_global_refc.lock);
1246 	if (imc_global_refc.id == IMC_DOMAIN_TRACE)
1247 		imc_global_refc.refc--;
1248 	spin_unlock(&imc_global_refc.lock);
1249 
1250 	return 0;
1251 }
1252 
1253 static int trace_imc_cpu_init(void)
1254 {
1255 	return cpuhp_setup_state(CPUHP_AP_PERF_POWERPC_TRACE_IMC_ONLINE,
1256 			  "perf/powerpc/imc_trace:online",
1257 			  ppc_trace_imc_cpu_online,
1258 			  ppc_trace_imc_cpu_offline);
1259 }
1260 
1261 static u64 get_trace_imc_event_base_addr(void)
1262 {
1263 	return (u64)per_cpu(trace_imc_mem, smp_processor_id());
1264 }
1265 
1266 /*
1267  * Function to parse trace-imc data obtained
1268  * and to prepare the perf sample.
1269  */
1270 static int trace_imc_prepare_sample(struct trace_imc_data *mem,
1271 				    struct perf_sample_data *data,
1272 				    u64 *prev_tb,
1273 				    struct perf_event_header *header,
1274 				    struct perf_event *event)
1275 {
1276 	/* Sanity checks for a valid record */
1277 	if (be64_to_cpu(READ_ONCE(mem->tb1)) > *prev_tb)
1278 		*prev_tb = be64_to_cpu(READ_ONCE(mem->tb1));
1279 	else
1280 		return -EINVAL;
1281 
1282 	if ((be64_to_cpu(READ_ONCE(mem->tb1)) & IMC_TRACE_RECORD_TB1_MASK) !=
1283 			 be64_to_cpu(READ_ONCE(mem->tb2)))
1284 		return -EINVAL;
1285 
1286 	/* Prepare perf sample */
1287 	data->ip =  be64_to_cpu(READ_ONCE(mem->ip));
1288 	data->period = event->hw.last_period;
1289 
1290 	header->type = PERF_RECORD_SAMPLE;
1291 	header->size = sizeof(*header) + event->header_size;
1292 	header->misc = 0;
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 			header->misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1298 			break;
1299 		case 1: /* MSR HV is 0 and PR is 1 */
1300 			header->misc |= PERF_RECORD_MISC_GUEST_USER;
1301 			break;
1302 		case 2: /* MSR HV is 1 and PR is 0 */
1303 			header->misc |= PERF_RECORD_MISC_KERNEL;
1304 			break;
1305 		case 3: /* MSR HV is 1 and PR is 1 */
1306 			header->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 			header->misc |= PERF_RECORD_MISC_KERNEL;
1315 		else
1316 			header->misc |= PERF_RECORD_MISC_USER;
1317 	}
1318 	perf_event_header__init_id(header, data, event);
1319 
1320 	return 0;
1321 }
1322 
1323 static void dump_trace_imc_data(struct perf_event *event)
1324 {
1325 	struct trace_imc_data *mem;
1326 	int i, ret;
1327 	u64 prev_tb = 0;
1328 
1329 	mem = (struct trace_imc_data *)get_trace_imc_event_base_addr();
1330 	for (i = 0; i < (trace_imc_mem_size / sizeof(struct trace_imc_data));
1331 		i++, mem++) {
1332 		struct perf_sample_data data;
1333 		struct perf_event_header header;
1334 
1335 		ret = trace_imc_prepare_sample(mem, &data, &prev_tb, &header, event);
1336 		if (ret) /* Exit, if not a valid record */
1337 			break;
1338 		else {
1339 			/* If this is a valid record, create the sample */
1340 			struct perf_output_handle handle;
1341 
1342 			if (perf_output_begin(&handle, &data, event, header.size))
1343 				return;
1344 
1345 			perf_output_sample(&handle, &header, &data, event);
1346 			perf_output_end(&handle);
1347 		}
1348 	}
1349 }
1350 
1351 static int trace_imc_event_add(struct perf_event *event, int flags)
1352 {
1353 	int core_id = smp_processor_id() / threads_per_core;
1354 	struct imc_pmu_ref *ref = NULL;
1355 	u64 local_mem, ldbar_value;
1356 
1357 	/* Set trace-imc bit in ldbar and load ldbar with per-thread memory address */
1358 	local_mem = get_trace_imc_event_base_addr();
1359 	ldbar_value = ((u64)local_mem & THREAD_IMC_LDBAR_MASK) | TRACE_IMC_ENABLE;
1360 
1361 	/* trace-imc reference count */
1362 	if (trace_imc_refc)
1363 		ref = &trace_imc_refc[core_id];
1364 	if (!ref) {
1365 		pr_debug("imc: Failed to get the event reference count\n");
1366 		return -EINVAL;
1367 	}
1368 
1369 	mtspr(SPRN_LDBAR, ldbar_value);
1370 	spin_lock(&ref->lock);
1371 	if (ref->refc == 0) {
1372 		if (opal_imc_counters_start(OPAL_IMC_COUNTERS_TRACE,
1373 				get_hard_smp_processor_id(smp_processor_id()))) {
1374 			spin_unlock(&ref->lock);
1375 			pr_err("trace-imc: Unable to start the counters for core %d\n", core_id);
1376 			return -EINVAL;
1377 		}
1378 	}
1379 	++ref->refc;
1380 	spin_unlock(&ref->lock);
1381 	return 0;
1382 }
1383 
1384 static void trace_imc_event_read(struct perf_event *event)
1385 {
1386 	return;
1387 }
1388 
1389 static void trace_imc_event_stop(struct perf_event *event, int flags)
1390 {
1391 	u64 local_mem = get_trace_imc_event_base_addr();
1392 	dump_trace_imc_data(event);
1393 	memset((void *)local_mem, 0, sizeof(u64));
1394 }
1395 
1396 static void trace_imc_event_start(struct perf_event *event, int flags)
1397 {
1398 	return;
1399 }
1400 
1401 static void trace_imc_event_del(struct perf_event *event, int flags)
1402 {
1403 	int core_id = smp_processor_id() / threads_per_core;
1404 	struct imc_pmu_ref *ref = NULL;
1405 
1406 	if (trace_imc_refc)
1407 		ref = &trace_imc_refc[core_id];
1408 	if (!ref) {
1409 		pr_debug("imc: Failed to get event reference count\n");
1410 		return;
1411 	}
1412 
1413 	spin_lock(&ref->lock);
1414 	ref->refc--;
1415 	if (ref->refc == 0) {
1416 		if (opal_imc_counters_stop(OPAL_IMC_COUNTERS_TRACE,
1417 				get_hard_smp_processor_id(smp_processor_id()))) {
1418 			spin_unlock(&ref->lock);
1419 			pr_err("trace-imc: Unable to stop the counters for core %d\n", core_id);
1420 			return;
1421 		}
1422 	} else if (ref->refc < 0) {
1423 		ref->refc = 0;
1424 	}
1425 	spin_unlock(&ref->lock);
1426 
1427 	trace_imc_event_stop(event, flags);
1428 }
1429 
1430 static int trace_imc_event_init(struct perf_event *event)
1431 {
1432 	if (event->attr.type != event->pmu->type)
1433 		return -ENOENT;
1434 
1435 	if (!perfmon_capable())
1436 		return -EACCES;
1437 
1438 	/* Return if this is a couting event */
1439 	if (event->attr.sample_period == 0)
1440 		return -ENOENT;
1441 
1442 	/*
1443 	 * Take the global lock, and make sure
1444 	 * no other thread is running any core/thread imc
1445 	 * events
1446 	 */
1447 	spin_lock(&imc_global_refc.lock);
1448 	if (imc_global_refc.id == 0 || imc_global_refc.id == IMC_DOMAIN_TRACE) {
1449 		/*
1450 		 * No core/thread imc events are running in the
1451 		 * system, so set the refc.id to trace-imc.
1452 		 */
1453 		imc_global_refc.id = IMC_DOMAIN_TRACE;
1454 		imc_global_refc.refc++;
1455 	} else {
1456 		spin_unlock(&imc_global_refc.lock);
1457 		return -EBUSY;
1458 	}
1459 	spin_unlock(&imc_global_refc.lock);
1460 
1461 	event->hw.idx = -1;
1462 
1463 	/*
1464 	 * There can only be a single PMU for perf_hw_context events which is assigned to
1465 	 * core PMU. Hence use "perf_sw_context" for trace_imc.
1466 	 */
1467 	event->pmu->task_ctx_nr = perf_sw_context;
1468 	event->destroy = reset_global_refc;
1469 	return 0;
1470 }
1471 
1472 /* update_pmu_ops : Populate the appropriate operations for "pmu" */
1473 static int update_pmu_ops(struct imc_pmu *pmu)
1474 {
1475 	pmu->pmu.task_ctx_nr = perf_invalid_context;
1476 	pmu->pmu.add = imc_event_add;
1477 	pmu->pmu.del = imc_event_stop;
1478 	pmu->pmu.start = imc_event_start;
1479 	pmu->pmu.stop = imc_event_stop;
1480 	pmu->pmu.read = imc_event_update;
1481 	pmu->pmu.attr_groups = pmu->attr_groups;
1482 	pmu->pmu.capabilities = PERF_PMU_CAP_NO_EXCLUDE;
1483 	pmu->attr_groups[IMC_FORMAT_ATTR] = &imc_format_group;
1484 
1485 	switch (pmu->domain) {
1486 	case IMC_DOMAIN_NEST:
1487 		pmu->pmu.event_init = nest_imc_event_init;
1488 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1489 		break;
1490 	case IMC_DOMAIN_CORE:
1491 		pmu->pmu.event_init = core_imc_event_init;
1492 		pmu->attr_groups[IMC_CPUMASK_ATTR] = &imc_pmu_cpumask_attr_group;
1493 		break;
1494 	case IMC_DOMAIN_THREAD:
1495 		pmu->pmu.event_init = thread_imc_event_init;
1496 		pmu->pmu.add = thread_imc_event_add;
1497 		pmu->pmu.del = thread_imc_event_del;
1498 		pmu->pmu.start_txn = thread_imc_pmu_start_txn;
1499 		pmu->pmu.cancel_txn = thread_imc_pmu_cancel_txn;
1500 		pmu->pmu.commit_txn = thread_imc_pmu_commit_txn;
1501 		break;
1502 	case IMC_DOMAIN_TRACE:
1503 		pmu->pmu.event_init = trace_imc_event_init;
1504 		pmu->pmu.add = trace_imc_event_add;
1505 		pmu->pmu.del = trace_imc_event_del;
1506 		pmu->pmu.start = trace_imc_event_start;
1507 		pmu->pmu.stop = trace_imc_event_stop;
1508 		pmu->pmu.read = trace_imc_event_read;
1509 		pmu->attr_groups[IMC_FORMAT_ATTR] = &trace_imc_format_group;
1510 		break;
1511 	default:
1512 		break;
1513 	}
1514 
1515 	return 0;
1516 }
1517 
1518 /* init_nest_pmu_ref: Initialize the imc_pmu_ref struct for all the nodes */
1519 static int init_nest_pmu_ref(void)
1520 {
1521 	int nid, i, cpu;
1522 
1523 	nest_imc_refc = kcalloc(num_possible_nodes(), sizeof(*nest_imc_refc),
1524 								GFP_KERNEL);
1525 
1526 	if (!nest_imc_refc)
1527 		return -ENOMEM;
1528 
1529 	i = 0;
1530 	for_each_node(nid) {
1531 		/*
1532 		 * Take the lock to avoid races while tracking the number of
1533 		 * sessions using the chip's nest pmu units.
1534 		 */
1535 		spin_lock_init(&nest_imc_refc[i].lock);
1536 
1537 		/*
1538 		 * Loop to init the "id" with the node_id. Variable "i" initialized to
1539 		 * 0 and will be used as index to the array. "i" will not go off the
1540 		 * end of the array since the "for_each_node" loops for "N_POSSIBLE"
1541 		 * nodes only.
1542 		 */
1543 		nest_imc_refc[i++].id = nid;
1544 	}
1545 
1546 	/*
1547 	 * Loop to init the per_cpu "local_nest_imc_refc" with the proper
1548 	 * "nest_imc_refc" index. This makes get_nest_pmu_ref() alot simple.
1549 	 */
1550 	for_each_possible_cpu(cpu) {
1551 		nid = cpu_to_node(cpu);
1552 		for (i = 0; i < num_possible_nodes(); i++) {
1553 			if (nest_imc_refc[i].id == nid) {
1554 				per_cpu(local_nest_imc_refc, cpu) = &nest_imc_refc[i];
1555 				break;
1556 			}
1557 		}
1558 	}
1559 	return 0;
1560 }
1561 
1562 static void cleanup_all_core_imc_memory(void)
1563 {
1564 	int i, nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1565 	struct imc_mem_info *ptr = core_imc_pmu->mem_info;
1566 	int size = core_imc_pmu->counter_mem_size;
1567 
1568 	/* mem_info will never be NULL */
1569 	for (i = 0; i < nr_cores; i++) {
1570 		if (ptr[i].vbase)
1571 			free_pages((u64)ptr[i].vbase, get_order(size));
1572 	}
1573 
1574 	kfree(ptr);
1575 	kfree(core_imc_refc);
1576 }
1577 
1578 static void thread_imc_ldbar_disable(void *dummy)
1579 {
1580 	/*
1581 	 * By setting 0th bit of LDBAR to zero, we disable thread-imc
1582 	 * updates to memory.
1583 	 */
1584 	mtspr(SPRN_LDBAR, (mfspr(SPRN_LDBAR) & (~(1UL << 63))));
1585 }
1586 
1587 void thread_imc_disable(void)
1588 {
1589 	on_each_cpu(thread_imc_ldbar_disable, NULL, 1);
1590 }
1591 
1592 static void cleanup_all_thread_imc_memory(void)
1593 {
1594 	int i, order = get_order(thread_imc_mem_size);
1595 
1596 	for_each_online_cpu(i) {
1597 		if (per_cpu(thread_imc_mem, i))
1598 			free_pages((u64)per_cpu(thread_imc_mem, i), order);
1599 
1600 	}
1601 }
1602 
1603 static void cleanup_all_trace_imc_memory(void)
1604 {
1605 	int i, order = get_order(trace_imc_mem_size);
1606 
1607 	for_each_online_cpu(i) {
1608 		if (per_cpu(trace_imc_mem, i))
1609 			free_pages((u64)per_cpu(trace_imc_mem, i), order);
1610 
1611 	}
1612 	kfree(trace_imc_refc);
1613 }
1614 
1615 /* Function to free the attr_groups which are dynamically allocated */
1616 static void imc_common_mem_free(struct imc_pmu *pmu_ptr)
1617 {
1618 	if (pmu_ptr->attr_groups[IMC_EVENT_ATTR])
1619 		kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]->attrs);
1620 	kfree(pmu_ptr->attr_groups[IMC_EVENT_ATTR]);
1621 }
1622 
1623 /*
1624  * Common function to unregister cpu hotplug callback and
1625  * free the memory.
1626  * TODO: Need to handle pmu unregistering, which will be
1627  * done in followup series.
1628  */
1629 static void imc_common_cpuhp_mem_free(struct imc_pmu *pmu_ptr)
1630 {
1631 	if (pmu_ptr->domain == IMC_DOMAIN_NEST) {
1632 		mutex_lock(&nest_init_lock);
1633 		if (nest_pmus == 1) {
1634 			cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_NEST_IMC_ONLINE);
1635 			kfree(nest_imc_refc);
1636 			kfree(per_nest_pmu_arr);
1637 			per_nest_pmu_arr = NULL;
1638 		}
1639 
1640 		if (nest_pmus > 0)
1641 			nest_pmus--;
1642 		mutex_unlock(&nest_init_lock);
1643 	}
1644 
1645 	/* Free core_imc memory */
1646 	if (pmu_ptr->domain == IMC_DOMAIN_CORE) {
1647 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_CORE_IMC_ONLINE);
1648 		cleanup_all_core_imc_memory();
1649 	}
1650 
1651 	/* Free thread_imc memory */
1652 	if (pmu_ptr->domain == IMC_DOMAIN_THREAD) {
1653 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_THREAD_IMC_ONLINE);
1654 		cleanup_all_thread_imc_memory();
1655 	}
1656 
1657 	if (pmu_ptr->domain == IMC_DOMAIN_TRACE) {
1658 		cpuhp_remove_state(CPUHP_AP_PERF_POWERPC_TRACE_IMC_ONLINE);
1659 		cleanup_all_trace_imc_memory();
1660 	}
1661 }
1662 
1663 /*
1664  * Function to unregister thread-imc if core-imc
1665  * is not registered.
1666  */
1667 void unregister_thread_imc(void)
1668 {
1669 	imc_common_cpuhp_mem_free(thread_imc_pmu);
1670 	imc_common_mem_free(thread_imc_pmu);
1671 	perf_pmu_unregister(&thread_imc_pmu->pmu);
1672 }
1673 
1674 /*
1675  * imc_mem_init : Function to support memory allocation for core imc.
1676  */
1677 static int imc_mem_init(struct imc_pmu *pmu_ptr, struct device_node *parent,
1678 								int pmu_index)
1679 {
1680 	const char *s;
1681 	int nr_cores, cpu, res = -ENOMEM;
1682 
1683 	if (of_property_read_string(parent, "name", &s))
1684 		return -ENODEV;
1685 
1686 	switch (pmu_ptr->domain) {
1687 	case IMC_DOMAIN_NEST:
1688 		/* Update the pmu name */
1689 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s_imc", "nest_", s);
1690 		if (!pmu_ptr->pmu.name)
1691 			goto err;
1692 
1693 		/* Needed for hotplug/migration */
1694 		if (!per_nest_pmu_arr) {
1695 			per_nest_pmu_arr = kcalloc(get_max_nest_dev() + 1,
1696 						sizeof(struct imc_pmu *),
1697 						GFP_KERNEL);
1698 			if (!per_nest_pmu_arr)
1699 				goto err;
1700 		}
1701 		per_nest_pmu_arr[pmu_index] = pmu_ptr;
1702 		break;
1703 	case IMC_DOMAIN_CORE:
1704 		/* Update the pmu name */
1705 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1706 		if (!pmu_ptr->pmu.name)
1707 			goto err;
1708 
1709 		nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1710 		pmu_ptr->mem_info = kcalloc(nr_cores, sizeof(struct imc_mem_info),
1711 								GFP_KERNEL);
1712 
1713 		if (!pmu_ptr->mem_info)
1714 			goto err;
1715 
1716 		core_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1717 								GFP_KERNEL);
1718 
1719 		if (!core_imc_refc) {
1720 			kfree(pmu_ptr->mem_info);
1721 			goto err;
1722 		}
1723 
1724 		core_imc_pmu = pmu_ptr;
1725 		break;
1726 	case IMC_DOMAIN_THREAD:
1727 		/* Update the pmu name */
1728 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1729 		if (!pmu_ptr->pmu.name)
1730 			goto err;
1731 
1732 		thread_imc_mem_size = pmu_ptr->counter_mem_size;
1733 		for_each_online_cpu(cpu) {
1734 			res = thread_imc_mem_alloc(cpu, pmu_ptr->counter_mem_size);
1735 			if (res) {
1736 				cleanup_all_thread_imc_memory();
1737 				goto err;
1738 			}
1739 		}
1740 
1741 		thread_imc_pmu = pmu_ptr;
1742 		break;
1743 	case IMC_DOMAIN_TRACE:
1744 		/* Update the pmu name */
1745 		pmu_ptr->pmu.name = kasprintf(GFP_KERNEL, "%s%s", s, "_imc");
1746 		if (!pmu_ptr->pmu.name)
1747 			return -ENOMEM;
1748 
1749 		nr_cores = DIV_ROUND_UP(num_possible_cpus(), threads_per_core);
1750 		trace_imc_refc = kcalloc(nr_cores, sizeof(struct imc_pmu_ref),
1751 								GFP_KERNEL);
1752 		if (!trace_imc_refc)
1753 			return -ENOMEM;
1754 
1755 		trace_imc_mem_size = pmu_ptr->counter_mem_size;
1756 		for_each_online_cpu(cpu) {
1757 			res = trace_imc_mem_alloc(cpu, trace_imc_mem_size);
1758 			if (res) {
1759 				cleanup_all_trace_imc_memory();
1760 				goto err;
1761 			}
1762 		}
1763 		break;
1764 	default:
1765 		return -EINVAL;
1766 	}
1767 
1768 	return 0;
1769 err:
1770 	return res;
1771 }
1772 
1773 /*
1774  * init_imc_pmu : Setup and register the IMC pmu device.
1775  *
1776  * @parent:	Device tree unit node
1777  * @pmu_ptr:	memory allocated for this pmu
1778  * @pmu_idx:	Count of nest pmc registered
1779  *
1780  * init_imc_pmu() setup pmu cpumask and registers for a cpu hotplug callback.
1781  * Handles failure cases and accordingly frees memory.
1782  */
1783 int init_imc_pmu(struct device_node *parent, struct imc_pmu *pmu_ptr, int pmu_idx)
1784 {
1785 	int ret;
1786 
1787 	ret = imc_mem_init(pmu_ptr, parent, pmu_idx);
1788 	if (ret)
1789 		goto err_free_mem;
1790 
1791 	switch (pmu_ptr->domain) {
1792 	case IMC_DOMAIN_NEST:
1793 		/*
1794 		* Nest imc pmu need only one cpu per chip, we initialize the
1795 		* cpumask for the first nest imc pmu and use the same for the
1796 		* rest. To handle the cpuhotplug callback unregister, we track
1797 		* the number of nest pmus in "nest_pmus".
1798 		*/
1799 		mutex_lock(&nest_init_lock);
1800 		if (nest_pmus == 0) {
1801 			ret = init_nest_pmu_ref();
1802 			if (ret) {
1803 				mutex_unlock(&nest_init_lock);
1804 				kfree(per_nest_pmu_arr);
1805 				per_nest_pmu_arr = NULL;
1806 				goto err_free_mem;
1807 			}
1808 			/* Register for cpu hotplug notification. */
1809 			ret = nest_pmu_cpumask_init();
1810 			if (ret) {
1811 				mutex_unlock(&nest_init_lock);
1812 				kfree(nest_imc_refc);
1813 				kfree(per_nest_pmu_arr);
1814 				per_nest_pmu_arr = NULL;
1815 				goto err_free_mem;
1816 			}
1817 		}
1818 		nest_pmus++;
1819 		mutex_unlock(&nest_init_lock);
1820 		break;
1821 	case IMC_DOMAIN_CORE:
1822 		ret = core_imc_pmu_cpumask_init();
1823 		if (ret) {
1824 			cleanup_all_core_imc_memory();
1825 			goto err_free_mem;
1826 		}
1827 
1828 		break;
1829 	case IMC_DOMAIN_THREAD:
1830 		ret = thread_imc_cpu_init();
1831 		if (ret) {
1832 			cleanup_all_thread_imc_memory();
1833 			goto err_free_mem;
1834 		}
1835 
1836 		break;
1837 	case IMC_DOMAIN_TRACE:
1838 		ret = trace_imc_cpu_init();
1839 		if (ret) {
1840 			cleanup_all_trace_imc_memory();
1841 			goto err_free_mem;
1842 		}
1843 
1844 		break;
1845 	default:
1846 		return  -EINVAL;	/* Unknown domain */
1847 	}
1848 
1849 	ret = update_events_in_group(parent, pmu_ptr);
1850 	if (ret)
1851 		goto err_free_cpuhp_mem;
1852 
1853 	ret = update_pmu_ops(pmu_ptr);
1854 	if (ret)
1855 		goto err_free_cpuhp_mem;
1856 
1857 	ret = perf_pmu_register(&pmu_ptr->pmu, pmu_ptr->pmu.name, -1);
1858 	if (ret)
1859 		goto err_free_cpuhp_mem;
1860 
1861 	pr_debug("%s performance monitor hardware support registered\n",
1862 							pmu_ptr->pmu.name);
1863 
1864 	return 0;
1865 
1866 err_free_cpuhp_mem:
1867 	imc_common_cpuhp_mem_free(pmu_ptr);
1868 err_free_mem:
1869 	imc_common_mem_free(pmu_ptr);
1870 	return ret;
1871 }
1872