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