xref: /linux/drivers/hwtracing/coresight/coresight-etm4x-core.c (revision 34f7c6e7d4396090692a09789db231e12cb4762b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2014, The Linux Foundation. All rights reserved.
4  */
5 
6 #include <linux/bitops.h>
7 #include <linux/kernel.h>
8 #include <linux/moduleparam.h>
9 #include <linux/init.h>
10 #include <linux/types.h>
11 #include <linux/device.h>
12 #include <linux/io.h>
13 #include <linux/err.h>
14 #include <linux/fs.h>
15 #include <linux/slab.h>
16 #include <linux/delay.h>
17 #include <linux/smp.h>
18 #include <linux/sysfs.h>
19 #include <linux/stat.h>
20 #include <linux/clk.h>
21 #include <linux/cpu.h>
22 #include <linux/cpu_pm.h>
23 #include <linux/coresight.h>
24 #include <linux/coresight-pmu.h>
25 #include <linux/pm_wakeup.h>
26 #include <linux/amba/bus.h>
27 #include <linux/seq_file.h>
28 #include <linux/uaccess.h>
29 #include <linux/perf_event.h>
30 #include <linux/platform_device.h>
31 #include <linux/pm_runtime.h>
32 #include <linux/property.h>
33 
34 #include <asm/barrier.h>
35 #include <asm/sections.h>
36 #include <asm/sysreg.h>
37 #include <asm/local.h>
38 #include <asm/virt.h>
39 
40 #include "coresight-etm4x.h"
41 #include "coresight-etm-perf.h"
42 #include "coresight-etm4x-cfg.h"
43 #include "coresight-self-hosted-trace.h"
44 #include "coresight-syscfg.h"
45 
46 static int boot_enable;
47 module_param(boot_enable, int, 0444);
48 MODULE_PARM_DESC(boot_enable, "Enable tracing on boot");
49 
50 #define PARAM_PM_SAVE_FIRMWARE	  0 /* save self-hosted state as per firmware */
51 #define PARAM_PM_SAVE_NEVER	  1 /* never save any state */
52 #define PARAM_PM_SAVE_SELF_HOSTED 2 /* save self-hosted state only */
53 
54 static int pm_save_enable = PARAM_PM_SAVE_FIRMWARE;
55 module_param(pm_save_enable, int, 0444);
56 MODULE_PARM_DESC(pm_save_enable,
57 	"Save/restore state on power down: 1 = never, 2 = self-hosted");
58 
59 static struct etmv4_drvdata *etmdrvdata[NR_CPUS];
60 static void etm4_set_default_config(struct etmv4_config *config);
61 static int etm4_set_event_filters(struct etmv4_drvdata *drvdata,
62 				  struct perf_event *event);
63 static u64 etm4_get_access_type(struct etmv4_config *config);
64 
65 static enum cpuhp_state hp_online;
66 
67 struct etm4_init_arg {
68 	unsigned int		pid;
69 	struct etmv4_drvdata	*drvdata;
70 	struct csdev_access	*csa;
71 };
72 
73 /*
74  * Check if TRCSSPCICRn(i) is implemented for a given instance.
75  *
76  * TRCSSPCICRn is implemented only if :
77  *	TRCSSPCICR<n> is present only if all of the following are true:
78  *		TRCIDR4.NUMSSCC > n.
79  *		TRCIDR4.NUMPC > 0b0000 .
80  *		TRCSSCSR<n>.PC == 0b1
81  */
82 static inline bool etm4x_sspcicrn_present(struct etmv4_drvdata *drvdata, int n)
83 {
84 	return (n < drvdata->nr_ss_cmp) &&
85 	       drvdata->nr_pe &&
86 	       (drvdata->config.ss_status[n] & TRCSSCSRn_PC);
87 }
88 
89 u64 etm4x_sysreg_read(u32 offset, bool _relaxed, bool _64bit)
90 {
91 	u64 res = 0;
92 
93 	switch (offset) {
94 	ETM4x_READ_SYSREG_CASES(res)
95 	default :
96 		pr_warn_ratelimited("etm4x: trying to read unsupported register @%x\n",
97 			 offset);
98 	}
99 
100 	if (!_relaxed)
101 		__iormb(res);	/* Imitate the !relaxed I/O helpers */
102 
103 	return res;
104 }
105 
106 void etm4x_sysreg_write(u64 val, u32 offset, bool _relaxed, bool _64bit)
107 {
108 	if (!_relaxed)
109 		__iowmb();	/* Imitate the !relaxed I/O helpers */
110 	if (!_64bit)
111 		val &= GENMASK(31, 0);
112 
113 	switch (offset) {
114 	ETM4x_WRITE_SYSREG_CASES(val)
115 	default :
116 		pr_warn_ratelimited("etm4x: trying to write to unsupported register @%x\n",
117 			offset);
118 	}
119 }
120 
121 static u64 ete_sysreg_read(u32 offset, bool _relaxed, bool _64bit)
122 {
123 	u64 res = 0;
124 
125 	switch (offset) {
126 	ETE_READ_CASES(res)
127 	default :
128 		pr_warn_ratelimited("ete: trying to read unsupported register @%x\n",
129 				    offset);
130 	}
131 
132 	if (!_relaxed)
133 		__iormb(res);	/* Imitate the !relaxed I/O helpers */
134 
135 	return res;
136 }
137 
138 static void ete_sysreg_write(u64 val, u32 offset, bool _relaxed, bool _64bit)
139 {
140 	if (!_relaxed)
141 		__iowmb();	/* Imitate the !relaxed I/O helpers */
142 	if (!_64bit)
143 		val &= GENMASK(31, 0);
144 
145 	switch (offset) {
146 	ETE_WRITE_CASES(val)
147 	default :
148 		pr_warn_ratelimited("ete: trying to write to unsupported register @%x\n",
149 				    offset);
150 	}
151 }
152 
153 static void etm_detect_os_lock(struct etmv4_drvdata *drvdata,
154 			       struct csdev_access *csa)
155 {
156 	u32 oslsr = etm4x_relaxed_read32(csa, TRCOSLSR);
157 
158 	drvdata->os_lock_model = ETM_OSLSR_OSLM(oslsr);
159 }
160 
161 static void etm_write_os_lock(struct etmv4_drvdata *drvdata,
162 			      struct csdev_access *csa, u32 val)
163 {
164 	val = !!val;
165 
166 	switch (drvdata->os_lock_model) {
167 	case ETM_OSLOCK_PRESENT:
168 		etm4x_relaxed_write32(csa, val, TRCOSLAR);
169 		break;
170 	case ETM_OSLOCK_PE:
171 		write_sysreg_s(val, SYS_OSLAR_EL1);
172 		break;
173 	default:
174 		pr_warn_once("CPU%d: Unsupported Trace OSLock model: %x\n",
175 			     smp_processor_id(), drvdata->os_lock_model);
176 		fallthrough;
177 	case ETM_OSLOCK_NI:
178 		return;
179 	}
180 	isb();
181 }
182 
183 static inline void etm4_os_unlock_csa(struct etmv4_drvdata *drvdata,
184 				      struct csdev_access *csa)
185 {
186 	WARN_ON(drvdata->cpu != smp_processor_id());
187 
188 	/* Writing 0 to OS Lock unlocks the trace unit registers */
189 	etm_write_os_lock(drvdata, csa, 0x0);
190 	drvdata->os_unlock = true;
191 }
192 
193 static void etm4_os_unlock(struct etmv4_drvdata *drvdata)
194 {
195 	if (!WARN_ON(!drvdata->csdev))
196 		etm4_os_unlock_csa(drvdata, &drvdata->csdev->access);
197 }
198 
199 static void etm4_os_lock(struct etmv4_drvdata *drvdata)
200 {
201 	if (WARN_ON(!drvdata->csdev))
202 		return;
203 	/* Writing 0x1 to OS Lock locks the trace registers */
204 	etm_write_os_lock(drvdata, &drvdata->csdev->access, 0x1);
205 	drvdata->os_unlock = false;
206 }
207 
208 static void etm4_cs_lock(struct etmv4_drvdata *drvdata,
209 			 struct csdev_access *csa)
210 {
211 	/* Software Lock is only accessible via memory mapped interface */
212 	if (csa->io_mem)
213 		CS_LOCK(csa->base);
214 }
215 
216 static void etm4_cs_unlock(struct etmv4_drvdata *drvdata,
217 			   struct csdev_access *csa)
218 {
219 	if (csa->io_mem)
220 		CS_UNLOCK(csa->base);
221 }
222 
223 static int etm4_cpu_id(struct coresight_device *csdev)
224 {
225 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
226 
227 	return drvdata->cpu;
228 }
229 
230 static int etm4_trace_id(struct coresight_device *csdev)
231 {
232 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
233 
234 	return drvdata->trcid;
235 }
236 
237 struct etm4_enable_arg {
238 	struct etmv4_drvdata *drvdata;
239 	int rc;
240 };
241 
242 /*
243  * etm4x_prohibit_trace - Prohibit the CPU from tracing at all ELs.
244  * When the CPU supports FEAT_TRF, we could move the ETM to a trace
245  * prohibited state by filtering the Exception levels via TRFCR_EL1.
246  */
247 static void etm4x_prohibit_trace(struct etmv4_drvdata *drvdata)
248 {
249 	/* If the CPU doesn't support FEAT_TRF, nothing to do */
250 	if (!drvdata->trfcr)
251 		return;
252 	cpu_prohibit_trace();
253 }
254 
255 /*
256  * etm4x_allow_trace - Allow CPU tracing in the respective ELs,
257  * as configured by the drvdata->config.mode for the current
258  * session. Even though we have TRCVICTLR bits to filter the
259  * trace in the ELs, it doesn't prevent the ETM from generating
260  * a packet (e.g, TraceInfo) that might contain the addresses from
261  * the excluded levels. Thus we use the additional controls provided
262  * via the Trace Filtering controls (FEAT_TRF) to make sure no trace
263  * is generated for the excluded ELs.
264  */
265 static void etm4x_allow_trace(struct etmv4_drvdata *drvdata)
266 {
267 	u64 trfcr = drvdata->trfcr;
268 
269 	/* If the CPU doesn't support FEAT_TRF, nothing to do */
270 	if (!trfcr)
271 		return;
272 
273 	if (drvdata->config.mode & ETM_MODE_EXCL_KERN)
274 		trfcr &= ~TRFCR_ELx_ExTRE;
275 	if (drvdata->config.mode & ETM_MODE_EXCL_USER)
276 		trfcr &= ~TRFCR_ELx_E0TRE;
277 
278 	write_trfcr(trfcr);
279 }
280 
281 #ifdef CONFIG_ETM4X_IMPDEF_FEATURE
282 
283 #define HISI_HIP08_AMBA_ID		0x000b6d01
284 #define ETM4_AMBA_MASK			0xfffff
285 #define HISI_HIP08_CORE_COMMIT_MASK	0x3000
286 #define HISI_HIP08_CORE_COMMIT_SHIFT	12
287 #define HISI_HIP08_CORE_COMMIT_FULL	0b00
288 #define HISI_HIP08_CORE_COMMIT_LVL_1	0b01
289 #define HISI_HIP08_CORE_COMMIT_REG	sys_reg(3, 1, 15, 2, 5)
290 
291 struct etm4_arch_features {
292 	void (*arch_callback)(bool enable);
293 };
294 
295 static bool etm4_hisi_match_pid(unsigned int id)
296 {
297 	return (id & ETM4_AMBA_MASK) == HISI_HIP08_AMBA_ID;
298 }
299 
300 static void etm4_hisi_config_core_commit(bool enable)
301 {
302 	u8 commit = enable ? HISI_HIP08_CORE_COMMIT_LVL_1 :
303 		    HISI_HIP08_CORE_COMMIT_FULL;
304 	u64 val;
305 
306 	/*
307 	 * bit 12 and 13 of HISI_HIP08_CORE_COMMIT_REG are used together
308 	 * to set core-commit, 2'b00 means cpu is at full speed, 2'b01,
309 	 * 2'b10, 2'b11 mean reduce pipeline speed, and 2'b01 means level-1
310 	 * speed(minimun value). So bit 12 and 13 should be cleared together.
311 	 */
312 	val = read_sysreg_s(HISI_HIP08_CORE_COMMIT_REG);
313 	val &= ~HISI_HIP08_CORE_COMMIT_MASK;
314 	val |= commit << HISI_HIP08_CORE_COMMIT_SHIFT;
315 	write_sysreg_s(val, HISI_HIP08_CORE_COMMIT_REG);
316 }
317 
318 static struct etm4_arch_features etm4_features[] = {
319 	[ETM4_IMPDEF_HISI_CORE_COMMIT] = {
320 		.arch_callback = etm4_hisi_config_core_commit,
321 	},
322 	{},
323 };
324 
325 static void etm4_enable_arch_specific(struct etmv4_drvdata *drvdata)
326 {
327 	struct etm4_arch_features *ftr;
328 	int bit;
329 
330 	for_each_set_bit(bit, drvdata->arch_features, ETM4_IMPDEF_FEATURE_MAX) {
331 		ftr = &etm4_features[bit];
332 
333 		if (ftr->arch_callback)
334 			ftr->arch_callback(true);
335 	}
336 }
337 
338 static void etm4_disable_arch_specific(struct etmv4_drvdata *drvdata)
339 {
340 	struct etm4_arch_features *ftr;
341 	int bit;
342 
343 	for_each_set_bit(bit, drvdata->arch_features, ETM4_IMPDEF_FEATURE_MAX) {
344 		ftr = &etm4_features[bit];
345 
346 		if (ftr->arch_callback)
347 			ftr->arch_callback(false);
348 	}
349 }
350 
351 static void etm4_check_arch_features(struct etmv4_drvdata *drvdata,
352 				      unsigned int id)
353 {
354 	if (etm4_hisi_match_pid(id))
355 		set_bit(ETM4_IMPDEF_HISI_CORE_COMMIT, drvdata->arch_features);
356 }
357 #else
358 static void etm4_enable_arch_specific(struct etmv4_drvdata *drvdata)
359 {
360 }
361 
362 static void etm4_disable_arch_specific(struct etmv4_drvdata *drvdata)
363 {
364 }
365 
366 static void etm4_check_arch_features(struct etmv4_drvdata *drvdata,
367 				     unsigned int id)
368 {
369 }
370 #endif /* CONFIG_ETM4X_IMPDEF_FEATURE */
371 
372 static int etm4_enable_hw(struct etmv4_drvdata *drvdata)
373 {
374 	int i, rc;
375 	struct etmv4_config *config = &drvdata->config;
376 	struct coresight_device *csdev = drvdata->csdev;
377 	struct device *etm_dev = &csdev->dev;
378 	struct csdev_access *csa = &csdev->access;
379 
380 
381 	etm4_cs_unlock(drvdata, csa);
382 	etm4_enable_arch_specific(drvdata);
383 
384 	etm4_os_unlock(drvdata);
385 
386 	rc = coresight_claim_device_unlocked(csdev);
387 	if (rc)
388 		goto done;
389 
390 	/* Disable the trace unit before programming trace registers */
391 	etm4x_relaxed_write32(csa, 0, TRCPRGCTLR);
392 
393 	/*
394 	 * If we use system instructions, we need to synchronize the
395 	 * write to the TRCPRGCTLR, before accessing the TRCSTATR.
396 	 * See ARM IHI0064F, section
397 	 * "4.3.7 Synchronization of register updates"
398 	 */
399 	if (!csa->io_mem)
400 		isb();
401 
402 	/* wait for TRCSTATR.IDLE to go up */
403 	if (coresight_timeout(csa, TRCSTATR, TRCSTATR_IDLE_BIT, 1))
404 		dev_err(etm_dev,
405 			"timeout while waiting for Idle Trace Status\n");
406 	if (drvdata->nr_pe)
407 		etm4x_relaxed_write32(csa, config->pe_sel, TRCPROCSELR);
408 	etm4x_relaxed_write32(csa, config->cfg, TRCCONFIGR);
409 	/* nothing specific implemented */
410 	etm4x_relaxed_write32(csa, 0x0, TRCAUXCTLR);
411 	etm4x_relaxed_write32(csa, config->eventctrl0, TRCEVENTCTL0R);
412 	etm4x_relaxed_write32(csa, config->eventctrl1, TRCEVENTCTL1R);
413 	if (drvdata->stallctl)
414 		etm4x_relaxed_write32(csa, config->stall_ctrl, TRCSTALLCTLR);
415 	etm4x_relaxed_write32(csa, config->ts_ctrl, TRCTSCTLR);
416 	etm4x_relaxed_write32(csa, config->syncfreq, TRCSYNCPR);
417 	etm4x_relaxed_write32(csa, config->ccctlr, TRCCCCTLR);
418 	etm4x_relaxed_write32(csa, config->bb_ctrl, TRCBBCTLR);
419 	etm4x_relaxed_write32(csa, drvdata->trcid, TRCTRACEIDR);
420 	etm4x_relaxed_write32(csa, config->vinst_ctrl, TRCVICTLR);
421 	etm4x_relaxed_write32(csa, config->viiectlr, TRCVIIECTLR);
422 	etm4x_relaxed_write32(csa, config->vissctlr, TRCVISSCTLR);
423 	if (drvdata->nr_pe_cmp)
424 		etm4x_relaxed_write32(csa, config->vipcssctlr, TRCVIPCSSCTLR);
425 	for (i = 0; i < drvdata->nrseqstate - 1; i++)
426 		etm4x_relaxed_write32(csa, config->seq_ctrl[i], TRCSEQEVRn(i));
427 	etm4x_relaxed_write32(csa, config->seq_rst, TRCSEQRSTEVR);
428 	etm4x_relaxed_write32(csa, config->seq_state, TRCSEQSTR);
429 	etm4x_relaxed_write32(csa, config->ext_inp, TRCEXTINSELR);
430 	for (i = 0; i < drvdata->nr_cntr; i++) {
431 		etm4x_relaxed_write32(csa, config->cntrldvr[i], TRCCNTRLDVRn(i));
432 		etm4x_relaxed_write32(csa, config->cntr_ctrl[i], TRCCNTCTLRn(i));
433 		etm4x_relaxed_write32(csa, config->cntr_val[i], TRCCNTVRn(i));
434 	}
435 
436 	/*
437 	 * Resource selector pair 0 is always implemented and reserved.  As
438 	 * such start at 2.
439 	 */
440 	for (i = 2; i < drvdata->nr_resource * 2; i++)
441 		etm4x_relaxed_write32(csa, config->res_ctrl[i], TRCRSCTLRn(i));
442 
443 	for (i = 0; i < drvdata->nr_ss_cmp; i++) {
444 		/* always clear status bit on restart if using single-shot */
445 		if (config->ss_ctrl[i] || config->ss_pe_cmp[i])
446 			config->ss_status[i] &= ~BIT(31);
447 		etm4x_relaxed_write32(csa, config->ss_ctrl[i], TRCSSCCRn(i));
448 		etm4x_relaxed_write32(csa, config->ss_status[i], TRCSSCSRn(i));
449 		if (etm4x_sspcicrn_present(drvdata, i))
450 			etm4x_relaxed_write32(csa, config->ss_pe_cmp[i], TRCSSPCICRn(i));
451 	}
452 	for (i = 0; i < drvdata->nr_addr_cmp; i++) {
453 		etm4x_relaxed_write64(csa, config->addr_val[i], TRCACVRn(i));
454 		etm4x_relaxed_write64(csa, config->addr_acc[i], TRCACATRn(i));
455 	}
456 	for (i = 0; i < drvdata->numcidc; i++)
457 		etm4x_relaxed_write64(csa, config->ctxid_pid[i], TRCCIDCVRn(i));
458 	etm4x_relaxed_write32(csa, config->ctxid_mask0, TRCCIDCCTLR0);
459 	if (drvdata->numcidc > 4)
460 		etm4x_relaxed_write32(csa, config->ctxid_mask1, TRCCIDCCTLR1);
461 
462 	for (i = 0; i < drvdata->numvmidc; i++)
463 		etm4x_relaxed_write64(csa, config->vmid_val[i], TRCVMIDCVRn(i));
464 	etm4x_relaxed_write32(csa, config->vmid_mask0, TRCVMIDCCTLR0);
465 	if (drvdata->numvmidc > 4)
466 		etm4x_relaxed_write32(csa, config->vmid_mask1, TRCVMIDCCTLR1);
467 
468 	if (!drvdata->skip_power_up) {
469 		u32 trcpdcr = etm4x_relaxed_read32(csa, TRCPDCR);
470 
471 		/*
472 		 * Request to keep the trace unit powered and also
473 		 * emulation of powerdown
474 		 */
475 		etm4x_relaxed_write32(csa, trcpdcr | TRCPDCR_PU, TRCPDCR);
476 	}
477 
478 	/*
479 	 * ETE mandates that the TRCRSR is written to before
480 	 * enabling it.
481 	 */
482 	if (etm4x_is_ete(drvdata))
483 		etm4x_relaxed_write32(csa, TRCRSR_TA, TRCRSR);
484 
485 	etm4x_allow_trace(drvdata);
486 	/* Enable the trace unit */
487 	etm4x_relaxed_write32(csa, 1, TRCPRGCTLR);
488 
489 	/* Synchronize the register updates for sysreg access */
490 	if (!csa->io_mem)
491 		isb();
492 
493 	/* wait for TRCSTATR.IDLE to go back down to '0' */
494 	if (coresight_timeout(csa, TRCSTATR, TRCSTATR_IDLE_BIT, 0))
495 		dev_err(etm_dev,
496 			"timeout while waiting for Idle Trace Status\n");
497 
498 	/*
499 	 * As recommended by section 4.3.7 ("Synchronization when using the
500 	 * memory-mapped interface") of ARM IHI 0064D
501 	 */
502 	dsb(sy);
503 	isb();
504 
505 done:
506 	etm4_cs_lock(drvdata, csa);
507 
508 	dev_dbg(etm_dev, "cpu: %d enable smp call done: %d\n",
509 		drvdata->cpu, rc);
510 	return rc;
511 }
512 
513 static void etm4_enable_hw_smp_call(void *info)
514 {
515 	struct etm4_enable_arg *arg = info;
516 
517 	if (WARN_ON(!arg))
518 		return;
519 	arg->rc = etm4_enable_hw(arg->drvdata);
520 }
521 
522 /*
523  * The goal of function etm4_config_timestamp_event() is to configure a
524  * counter that will tell the tracer to emit a timestamp packet when it
525  * reaches zero.  This is done in order to get a more fine grained idea
526  * of when instructions are executed so that they can be correlated
527  * with execution on other CPUs.
528  *
529  * To do this the counter itself is configured to self reload and
530  * TRCRSCTLR1 (always true) used to get the counter to decrement.  From
531  * there a resource selector is configured with the counter and the
532  * timestamp control register to use the resource selector to trigger the
533  * event that will insert a timestamp packet in the stream.
534  */
535 static int etm4_config_timestamp_event(struct etmv4_drvdata *drvdata)
536 {
537 	int ctridx, ret = -EINVAL;
538 	int counter, rselector;
539 	u32 val = 0;
540 	struct etmv4_config *config = &drvdata->config;
541 
542 	/* No point in trying if we don't have at least one counter */
543 	if (!drvdata->nr_cntr)
544 		goto out;
545 
546 	/* Find a counter that hasn't been initialised */
547 	for (ctridx = 0; ctridx < drvdata->nr_cntr; ctridx++)
548 		if (config->cntr_val[ctridx] == 0)
549 			break;
550 
551 	/* All the counters have been configured already, bail out */
552 	if (ctridx == drvdata->nr_cntr) {
553 		pr_debug("%s: no available counter found\n", __func__);
554 		ret = -ENOSPC;
555 		goto out;
556 	}
557 
558 	/*
559 	 * Searching for an available resource selector to use, starting at
560 	 * '2' since every implementation has at least 2 resource selector.
561 	 * ETMIDR4 gives the number of resource selector _pairs_,
562 	 * hence multiply by 2.
563 	 */
564 	for (rselector = 2; rselector < drvdata->nr_resource * 2; rselector++)
565 		if (!config->res_ctrl[rselector])
566 			break;
567 
568 	if (rselector == drvdata->nr_resource * 2) {
569 		pr_debug("%s: no available resource selector found\n",
570 			 __func__);
571 		ret = -ENOSPC;
572 		goto out;
573 	}
574 
575 	/* Remember what counter we used */
576 	counter = 1 << ctridx;
577 
578 	/*
579 	 * Initialise original and reload counter value to the smallest
580 	 * possible value in order to get as much precision as we can.
581 	 */
582 	config->cntr_val[ctridx] = 1;
583 	config->cntrldvr[ctridx] = 1;
584 
585 	/* Set the trace counter control register */
586 	val =  0x1 << 16	|  /* Bit 16, reload counter automatically */
587 	       0x0 << 7		|  /* Select single resource selector */
588 	       0x1;		   /* Resource selector 1, i.e always true */
589 
590 	config->cntr_ctrl[ctridx] = val;
591 
592 	val = 0x2 << 16		| /* Group 0b0010 - Counter and sequencers */
593 	      counter << 0;	  /* Counter to use */
594 
595 	config->res_ctrl[rselector] = val;
596 
597 	val = 0x0 << 7		| /* Select single resource selector */
598 	      rselector;	  /* Resource selector */
599 
600 	config->ts_ctrl = val;
601 
602 	ret = 0;
603 out:
604 	return ret;
605 }
606 
607 static int etm4_parse_event_config(struct coresight_device *csdev,
608 				   struct perf_event *event)
609 {
610 	int ret = 0;
611 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
612 	struct etmv4_config *config = &drvdata->config;
613 	struct perf_event_attr *attr = &event->attr;
614 	unsigned long cfg_hash;
615 	int preset;
616 
617 	/* Clear configuration from previous run */
618 	memset(config, 0, sizeof(struct etmv4_config));
619 
620 	if (attr->exclude_kernel)
621 		config->mode = ETM_MODE_EXCL_KERN;
622 
623 	if (attr->exclude_user)
624 		config->mode = ETM_MODE_EXCL_USER;
625 
626 	/* Always start from the default config */
627 	etm4_set_default_config(config);
628 
629 	/* Configure filters specified on the perf cmd line, if any. */
630 	ret = etm4_set_event_filters(drvdata, event);
631 	if (ret)
632 		goto out;
633 
634 	/* Go from generic option to ETMv4 specifics */
635 	if (attr->config & BIT(ETM_OPT_CYCACC)) {
636 		config->cfg |= BIT(4);
637 		/* TRM: Must program this for cycacc to work */
638 		config->ccctlr = ETM_CYC_THRESHOLD_DEFAULT;
639 	}
640 	if (attr->config & BIT(ETM_OPT_TS)) {
641 		/*
642 		 * Configure timestamps to be emitted at regular intervals in
643 		 * order to correlate instructions executed on different CPUs
644 		 * (CPU-wide trace scenarios).
645 		 */
646 		ret = etm4_config_timestamp_event(drvdata);
647 
648 		/*
649 		 * No need to go further if timestamp intervals can't
650 		 * be configured.
651 		 */
652 		if (ret)
653 			goto out;
654 
655 		/* bit[11], Global timestamp tracing bit */
656 		config->cfg |= BIT(11);
657 	}
658 
659 	/* Only trace contextID when runs in root PID namespace */
660 	if ((attr->config & BIT(ETM_OPT_CTXTID)) &&
661 	    task_is_in_init_pid_ns(current))
662 		/* bit[6], Context ID tracing bit */
663 		config->cfg |= BIT(ETM4_CFG_BIT_CTXTID);
664 
665 	/*
666 	 * If set bit ETM_OPT_CTXTID2 in perf config, this asks to trace VMID
667 	 * for recording CONTEXTIDR_EL2.  Do not enable VMID tracing if the
668 	 * kernel is not running in EL2.
669 	 */
670 	if (attr->config & BIT(ETM_OPT_CTXTID2)) {
671 		if (!is_kernel_in_hyp_mode()) {
672 			ret = -EINVAL;
673 			goto out;
674 		}
675 
676 		/* Only trace virtual contextID when runs in root PID namespace */
677 		if (task_is_in_init_pid_ns(current))
678 			config->cfg |= BIT(ETM4_CFG_BIT_VMID) |
679 				       BIT(ETM4_CFG_BIT_VMID_OPT);
680 	}
681 
682 	/* return stack - enable if selected and supported */
683 	if ((attr->config & BIT(ETM_OPT_RETSTK)) && drvdata->retstack)
684 		/* bit[12], Return stack enable bit */
685 		config->cfg |= BIT(12);
686 
687 	/*
688 	 * Set any selected configuration and preset.
689 	 *
690 	 * This extracts the values of PMU_FORMAT_ATTR(configid) and PMU_FORMAT_ATTR(preset)
691 	 * in the perf attributes defined in coresight-etm-perf.c.
692 	 * configid uses bits 63:32 of attr->config2, preset uses bits 3:0 of attr->config.
693 	 * A zero configid means no configuration active, preset = 0 means no preset selected.
694 	 */
695 	if (attr->config2 & GENMASK_ULL(63, 32)) {
696 		cfg_hash = (u32)(attr->config2 >> 32);
697 		preset = attr->config & 0xF;
698 		ret = cscfg_csdev_enable_active_config(csdev, cfg_hash, preset);
699 	}
700 
701 out:
702 	return ret;
703 }
704 
705 static int etm4_enable_perf(struct coresight_device *csdev,
706 			    struct perf_event *event)
707 {
708 	int ret = 0;
709 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
710 
711 	if (WARN_ON_ONCE(drvdata->cpu != smp_processor_id())) {
712 		ret = -EINVAL;
713 		goto out;
714 	}
715 
716 	/* Configure the tracer based on the session's specifics */
717 	ret = etm4_parse_event_config(csdev, event);
718 	if (ret)
719 		goto out;
720 	/* And enable it */
721 	ret = etm4_enable_hw(drvdata);
722 
723 out:
724 	return ret;
725 }
726 
727 static int etm4_enable_sysfs(struct coresight_device *csdev)
728 {
729 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
730 	struct etm4_enable_arg arg = { };
731 	unsigned long cfg_hash;
732 	int ret, preset;
733 
734 	/* enable any config activated by configfs */
735 	cscfg_config_sysfs_get_active_cfg(&cfg_hash, &preset);
736 	if (cfg_hash) {
737 		ret = cscfg_csdev_enable_active_config(csdev, cfg_hash, preset);
738 		if (ret)
739 			return ret;
740 	}
741 
742 	spin_lock(&drvdata->spinlock);
743 
744 	/*
745 	 * Executing etm4_enable_hw on the cpu whose ETM is being enabled
746 	 * ensures that register writes occur when cpu is powered.
747 	 */
748 	arg.drvdata = drvdata;
749 	ret = smp_call_function_single(drvdata->cpu,
750 				       etm4_enable_hw_smp_call, &arg, 1);
751 	if (!ret)
752 		ret = arg.rc;
753 	if (!ret)
754 		drvdata->sticky_enable = true;
755 	spin_unlock(&drvdata->spinlock);
756 
757 	if (!ret)
758 		dev_dbg(&csdev->dev, "ETM tracing enabled\n");
759 	return ret;
760 }
761 
762 static int etm4_enable(struct coresight_device *csdev,
763 		       struct perf_event *event, u32 mode)
764 {
765 	int ret;
766 	u32 val;
767 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
768 
769 	val = local_cmpxchg(&drvdata->mode, CS_MODE_DISABLED, mode);
770 
771 	/* Someone is already using the tracer */
772 	if (val)
773 		return -EBUSY;
774 
775 	switch (mode) {
776 	case CS_MODE_SYSFS:
777 		ret = etm4_enable_sysfs(csdev);
778 		break;
779 	case CS_MODE_PERF:
780 		ret = etm4_enable_perf(csdev, event);
781 		break;
782 	default:
783 		ret = -EINVAL;
784 	}
785 
786 	/* The tracer didn't start */
787 	if (ret)
788 		local_set(&drvdata->mode, CS_MODE_DISABLED);
789 
790 	return ret;
791 }
792 
793 static void etm4_disable_hw(void *info)
794 {
795 	u32 control;
796 	struct etmv4_drvdata *drvdata = info;
797 	struct etmv4_config *config = &drvdata->config;
798 	struct coresight_device *csdev = drvdata->csdev;
799 	struct device *etm_dev = &csdev->dev;
800 	struct csdev_access *csa = &csdev->access;
801 	int i;
802 
803 	etm4_cs_unlock(drvdata, csa);
804 	etm4_disable_arch_specific(drvdata);
805 
806 	if (!drvdata->skip_power_up) {
807 		/* power can be removed from the trace unit now */
808 		control = etm4x_relaxed_read32(csa, TRCPDCR);
809 		control &= ~TRCPDCR_PU;
810 		etm4x_relaxed_write32(csa, control, TRCPDCR);
811 	}
812 
813 	control = etm4x_relaxed_read32(csa, TRCPRGCTLR);
814 
815 	/* EN, bit[0] Trace unit enable bit */
816 	control &= ~0x1;
817 
818 	/*
819 	 * If the CPU supports v8.4 Trace filter Control,
820 	 * set the ETM to trace prohibited region.
821 	 */
822 	etm4x_prohibit_trace(drvdata);
823 	/*
824 	 * Make sure everything completes before disabling, as recommended
825 	 * by section 7.3.77 ("TRCVICTLR, ViewInst Main Control Register,
826 	 * SSTATUS") of ARM IHI 0064D
827 	 */
828 	dsb(sy);
829 	isb();
830 	/* Trace synchronization barrier, is a nop if not supported */
831 	tsb_csync();
832 	etm4x_relaxed_write32(csa, control, TRCPRGCTLR);
833 
834 	/* wait for TRCSTATR.PMSTABLE to go to '1' */
835 	if (coresight_timeout(csa, TRCSTATR, TRCSTATR_PMSTABLE_BIT, 1))
836 		dev_err(etm_dev,
837 			"timeout while waiting for PM stable Trace Status\n");
838 	/* read the status of the single shot comparators */
839 	for (i = 0; i < drvdata->nr_ss_cmp; i++) {
840 		config->ss_status[i] =
841 			etm4x_relaxed_read32(csa, TRCSSCSRn(i));
842 	}
843 
844 	/* read back the current counter values */
845 	for (i = 0; i < drvdata->nr_cntr; i++) {
846 		config->cntr_val[i] =
847 			etm4x_relaxed_read32(csa, TRCCNTVRn(i));
848 	}
849 
850 	coresight_disclaim_device_unlocked(csdev);
851 	etm4_cs_lock(drvdata, csa);
852 
853 	dev_dbg(&drvdata->csdev->dev,
854 		"cpu: %d disable smp call done\n", drvdata->cpu);
855 }
856 
857 static int etm4_disable_perf(struct coresight_device *csdev,
858 			     struct perf_event *event)
859 {
860 	u32 control;
861 	struct etm_filters *filters = event->hw.addr_filters;
862 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
863 	struct perf_event_attr *attr = &event->attr;
864 
865 	if (WARN_ON_ONCE(drvdata->cpu != smp_processor_id()))
866 		return -EINVAL;
867 
868 	etm4_disable_hw(drvdata);
869 	/*
870 	 * The config_id occupies bits 63:32 of the config2 perf event attr
871 	 * field. If this is non-zero then we will have enabled a config.
872 	 */
873 	if (attr->config2 & GENMASK_ULL(63, 32))
874 		cscfg_csdev_disable_active_config(csdev);
875 
876 	/*
877 	 * Check if the start/stop logic was active when the unit was stopped.
878 	 * That way we can re-enable the start/stop logic when the process is
879 	 * scheduled again.  Configuration of the start/stop logic happens in
880 	 * function etm4_set_event_filters().
881 	 */
882 	control = etm4x_relaxed_read32(&csdev->access, TRCVICTLR);
883 	/* TRCVICTLR::SSSTATUS, bit[9] */
884 	filters->ssstatus = (control & BIT(9));
885 
886 	return 0;
887 }
888 
889 static void etm4_disable_sysfs(struct coresight_device *csdev)
890 {
891 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
892 
893 	/*
894 	 * Taking hotplug lock here protects from clocks getting disabled
895 	 * with tracing being left on (crash scenario) if user disable occurs
896 	 * after cpu online mask indicates the cpu is offline but before the
897 	 * DYING hotplug callback is serviced by the ETM driver.
898 	 */
899 	cpus_read_lock();
900 	spin_lock(&drvdata->spinlock);
901 
902 	/*
903 	 * Executing etm4_disable_hw on the cpu whose ETM is being disabled
904 	 * ensures that register writes occur when cpu is powered.
905 	 */
906 	smp_call_function_single(drvdata->cpu, etm4_disable_hw, drvdata, 1);
907 
908 	spin_unlock(&drvdata->spinlock);
909 	cpus_read_unlock();
910 
911 	dev_dbg(&csdev->dev, "ETM tracing disabled\n");
912 }
913 
914 static void etm4_disable(struct coresight_device *csdev,
915 			 struct perf_event *event)
916 {
917 	u32 mode;
918 	struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
919 
920 	/*
921 	 * For as long as the tracer isn't disabled another entity can't
922 	 * change its status.  As such we can read the status here without
923 	 * fearing it will change under us.
924 	 */
925 	mode = local_read(&drvdata->mode);
926 
927 	switch (mode) {
928 	case CS_MODE_DISABLED:
929 		break;
930 	case CS_MODE_SYSFS:
931 		etm4_disable_sysfs(csdev);
932 		break;
933 	case CS_MODE_PERF:
934 		etm4_disable_perf(csdev, event);
935 		break;
936 	}
937 
938 	if (mode)
939 		local_set(&drvdata->mode, CS_MODE_DISABLED);
940 }
941 
942 static const struct coresight_ops_source etm4_source_ops = {
943 	.cpu_id		= etm4_cpu_id,
944 	.trace_id	= etm4_trace_id,
945 	.enable		= etm4_enable,
946 	.disable	= etm4_disable,
947 };
948 
949 static const struct coresight_ops etm4_cs_ops = {
950 	.source_ops	= &etm4_source_ops,
951 };
952 
953 static inline bool cpu_supports_sysreg_trace(void)
954 {
955 	u64 dfr0 = read_sysreg_s(SYS_ID_AA64DFR0_EL1);
956 
957 	return ((dfr0 >> ID_AA64DFR0_TRACEVER_SHIFT) & 0xfUL) > 0;
958 }
959 
960 static bool etm4_init_sysreg_access(struct etmv4_drvdata *drvdata,
961 				    struct csdev_access *csa)
962 {
963 	u32 devarch;
964 
965 	if (!cpu_supports_sysreg_trace())
966 		return false;
967 
968 	/*
969 	 * ETMs implementing sysreg access must implement TRCDEVARCH.
970 	 */
971 	devarch = read_etm4x_sysreg_const_offset(TRCDEVARCH);
972 	switch (devarch & ETM_DEVARCH_ID_MASK) {
973 	case ETM_DEVARCH_ETMv4x_ARCH:
974 		*csa = (struct csdev_access) {
975 			.io_mem	= false,
976 			.read	= etm4x_sysreg_read,
977 			.write	= etm4x_sysreg_write,
978 		};
979 		break;
980 	case ETM_DEVARCH_ETE_ARCH:
981 		*csa = (struct csdev_access) {
982 			.io_mem	= false,
983 			.read	= ete_sysreg_read,
984 			.write	= ete_sysreg_write,
985 		};
986 		break;
987 	default:
988 		return false;
989 	}
990 
991 	drvdata->arch = etm_devarch_to_arch(devarch);
992 	return true;
993 }
994 
995 static bool etm4_init_iomem_access(struct etmv4_drvdata *drvdata,
996 				   struct csdev_access *csa)
997 {
998 	u32 devarch = readl_relaxed(drvdata->base + TRCDEVARCH);
999 	u32 idr1 = readl_relaxed(drvdata->base + TRCIDR1);
1000 
1001 	/*
1002 	 * All ETMs must implement TRCDEVARCH to indicate that
1003 	 * the component is an ETMv4. To support any broken
1004 	 * implementations we fall back to TRCIDR1 check, which
1005 	 * is not really reliable.
1006 	 */
1007 	if ((devarch & ETM_DEVARCH_ID_MASK) == ETM_DEVARCH_ETMv4x_ARCH) {
1008 		drvdata->arch = etm_devarch_to_arch(devarch);
1009 	} else {
1010 		pr_warn("CPU%d: ETM4x incompatible TRCDEVARCH: %x, falling back to TRCIDR1\n",
1011 			smp_processor_id(), devarch);
1012 
1013 		if (ETM_TRCIDR1_ARCH_MAJOR(idr1) != ETM_TRCIDR1_ARCH_ETMv4)
1014 			return false;
1015 		drvdata->arch = etm_trcidr_to_arch(idr1);
1016 	}
1017 
1018 	*csa = CSDEV_ACCESS_IOMEM(drvdata->base);
1019 	return true;
1020 }
1021 
1022 static bool etm4_init_csdev_access(struct etmv4_drvdata *drvdata,
1023 				   struct csdev_access *csa)
1024 {
1025 	/*
1026 	 * Always choose the memory mapped io, if there is
1027 	 * a memory map to prevent sysreg access on broken
1028 	 * systems.
1029 	 */
1030 	if (drvdata->base)
1031 		return etm4_init_iomem_access(drvdata, csa);
1032 
1033 	if (etm4_init_sysreg_access(drvdata, csa))
1034 		return true;
1035 
1036 	return false;
1037 }
1038 
1039 static void cpu_detect_trace_filtering(struct etmv4_drvdata *drvdata)
1040 {
1041 	u64 dfr0 = read_sysreg(id_aa64dfr0_el1);
1042 	u64 trfcr;
1043 
1044 	drvdata->trfcr = 0;
1045 	if (!cpuid_feature_extract_unsigned_field(dfr0, ID_AA64DFR0_TRACE_FILT_SHIFT))
1046 		return;
1047 
1048 	/*
1049 	 * If the CPU supports v8.4 SelfHosted Tracing, enable
1050 	 * tracing at the kernel EL and EL0, forcing to use the
1051 	 * virtual time as the timestamp.
1052 	 */
1053 	trfcr = (TRFCR_ELx_TS_VIRTUAL |
1054 		 TRFCR_ELx_ExTRE |
1055 		 TRFCR_ELx_E0TRE);
1056 
1057 	/* If we are running at EL2, allow tracing the CONTEXTIDR_EL2. */
1058 	if (is_kernel_in_hyp_mode())
1059 		trfcr |= TRFCR_EL2_CX;
1060 
1061 	drvdata->trfcr = trfcr;
1062 }
1063 
1064 static void etm4_init_arch_data(void *info)
1065 {
1066 	u32 etmidr0;
1067 	u32 etmidr2;
1068 	u32 etmidr3;
1069 	u32 etmidr4;
1070 	u32 etmidr5;
1071 	struct etm4_init_arg *init_arg = info;
1072 	struct etmv4_drvdata *drvdata;
1073 	struct csdev_access *csa;
1074 	int i;
1075 
1076 	drvdata = init_arg->drvdata;
1077 	csa = init_arg->csa;
1078 
1079 	/*
1080 	 * If we are unable to detect the access mechanism,
1081 	 * or unable to detect the trace unit type, fail
1082 	 * early.
1083 	 */
1084 	if (!etm4_init_csdev_access(drvdata, csa))
1085 		return;
1086 
1087 	/* Detect the support for OS Lock before we actually use it */
1088 	etm_detect_os_lock(drvdata, csa);
1089 
1090 	/* Make sure all registers are accessible */
1091 	etm4_os_unlock_csa(drvdata, csa);
1092 	etm4_cs_unlock(drvdata, csa);
1093 
1094 	etm4_check_arch_features(drvdata, init_arg->pid);
1095 
1096 	/* find all capabilities of the tracing unit */
1097 	etmidr0 = etm4x_relaxed_read32(csa, TRCIDR0);
1098 
1099 	/* INSTP0, bits[2:1] P0 tracing support field */
1100 	if (BMVAL(etmidr0, 1, 2) == 0b11)
1101 		drvdata->instrp0 = true;
1102 	else
1103 		drvdata->instrp0 = false;
1104 
1105 	/* TRCBB, bit[5] Branch broadcast tracing support bit */
1106 	if (BMVAL(etmidr0, 5, 5))
1107 		drvdata->trcbb = true;
1108 	else
1109 		drvdata->trcbb = false;
1110 
1111 	/* TRCCOND, bit[6] Conditional instruction tracing support bit */
1112 	if (BMVAL(etmidr0, 6, 6))
1113 		drvdata->trccond = true;
1114 	else
1115 		drvdata->trccond = false;
1116 
1117 	/* TRCCCI, bit[7] Cycle counting instruction bit */
1118 	if (BMVAL(etmidr0, 7, 7))
1119 		drvdata->trccci = true;
1120 	else
1121 		drvdata->trccci = false;
1122 
1123 	/* RETSTACK, bit[9] Return stack bit */
1124 	if (BMVAL(etmidr0, 9, 9))
1125 		drvdata->retstack = true;
1126 	else
1127 		drvdata->retstack = false;
1128 
1129 	/* NUMEVENT, bits[11:10] Number of events field */
1130 	drvdata->nr_event = BMVAL(etmidr0, 10, 11);
1131 	/* QSUPP, bits[16:15] Q element support field */
1132 	drvdata->q_support = BMVAL(etmidr0, 15, 16);
1133 	/* TSSIZE, bits[28:24] Global timestamp size field */
1134 	drvdata->ts_size = BMVAL(etmidr0, 24, 28);
1135 
1136 	/* maximum size of resources */
1137 	etmidr2 = etm4x_relaxed_read32(csa, TRCIDR2);
1138 	/* CIDSIZE, bits[9:5] Indicates the Context ID size */
1139 	drvdata->ctxid_size = BMVAL(etmidr2, 5, 9);
1140 	/* VMIDSIZE, bits[14:10] Indicates the VMID size */
1141 	drvdata->vmid_size = BMVAL(etmidr2, 10, 14);
1142 	/* CCSIZE, bits[28:25] size of the cycle counter in bits minus 12 */
1143 	drvdata->ccsize = BMVAL(etmidr2, 25, 28);
1144 
1145 	etmidr3 = etm4x_relaxed_read32(csa, TRCIDR3);
1146 	/* CCITMIN, bits[11:0] minimum threshold value that can be programmed */
1147 	drvdata->ccitmin = BMVAL(etmidr3, 0, 11);
1148 	/* EXLEVEL_S, bits[19:16] Secure state instruction tracing */
1149 	drvdata->s_ex_level = BMVAL(etmidr3, 16, 19);
1150 	drvdata->config.s_ex_level = drvdata->s_ex_level;
1151 	/* EXLEVEL_NS, bits[23:20] Non-secure state instruction tracing */
1152 	drvdata->ns_ex_level = BMVAL(etmidr3, 20, 23);
1153 
1154 	/*
1155 	 * TRCERR, bit[24] whether a trace unit can trace a
1156 	 * system error exception.
1157 	 */
1158 	if (BMVAL(etmidr3, 24, 24))
1159 		drvdata->trc_error = true;
1160 	else
1161 		drvdata->trc_error = false;
1162 
1163 	/* SYNCPR, bit[25] implementation has a fixed synchronization period? */
1164 	if (BMVAL(etmidr3, 25, 25))
1165 		drvdata->syncpr = true;
1166 	else
1167 		drvdata->syncpr = false;
1168 
1169 	/* STALLCTL, bit[26] is stall control implemented? */
1170 	if (BMVAL(etmidr3, 26, 26))
1171 		drvdata->stallctl = true;
1172 	else
1173 		drvdata->stallctl = false;
1174 
1175 	/* SYSSTALL, bit[27] implementation can support stall control? */
1176 	if (BMVAL(etmidr3, 27, 27))
1177 		drvdata->sysstall = true;
1178 	else
1179 		drvdata->sysstall = false;
1180 
1181 	/*
1182 	 * NUMPROC - the number of PEs available for tracing, 5bits
1183 	 *         = TRCIDR3.bits[13:12]bits[30:28]
1184 	 *  bits[4:3] = TRCIDR3.bits[13:12] (since etm-v4.2, otherwise RES0)
1185 	 *  bits[3:0] = TRCIDR3.bits[30:28]
1186 	 */
1187 	drvdata->nr_pe = (BMVAL(etmidr3, 12, 13) << 3) | BMVAL(etmidr3, 28, 30);
1188 
1189 	/* NOOVERFLOW, bit[31] is trace overflow prevention supported */
1190 	if (BMVAL(etmidr3, 31, 31))
1191 		drvdata->nooverflow = true;
1192 	else
1193 		drvdata->nooverflow = false;
1194 
1195 	/* number of resources trace unit supports */
1196 	etmidr4 = etm4x_relaxed_read32(csa, TRCIDR4);
1197 	/* NUMACPAIRS, bits[0:3] number of addr comparator pairs for tracing */
1198 	drvdata->nr_addr_cmp = BMVAL(etmidr4, 0, 3);
1199 	/* NUMPC, bits[15:12] number of PE comparator inputs for tracing */
1200 	drvdata->nr_pe_cmp = BMVAL(etmidr4, 12, 15);
1201 	/*
1202 	 * NUMRSPAIR, bits[19:16]
1203 	 * The number of resource pairs conveyed by the HW starts at 0, i.e a
1204 	 * value of 0x0 indicate 1 resource pair, 0x1 indicate two and so on.
1205 	 * As such add 1 to the value of NUMRSPAIR for a better representation.
1206 	 *
1207 	 * For ETM v4.3 and later, 0x0 means 0, and no pairs are available -
1208 	 * the default TRUE and FALSE resource selectors are omitted.
1209 	 * Otherwise for values 0x1 and above the number is N + 1 as per v4.2.
1210 	 */
1211 	drvdata->nr_resource = BMVAL(etmidr4, 16, 19);
1212 	if ((drvdata->arch < ETM_ARCH_V4_3) || (drvdata->nr_resource > 0))
1213 		drvdata->nr_resource += 1;
1214 	/*
1215 	 * NUMSSCC, bits[23:20] the number of single-shot
1216 	 * comparator control for tracing. Read any status regs as these
1217 	 * also contain RO capability data.
1218 	 */
1219 	drvdata->nr_ss_cmp = BMVAL(etmidr4, 20, 23);
1220 	for (i = 0; i < drvdata->nr_ss_cmp; i++) {
1221 		drvdata->config.ss_status[i] =
1222 			etm4x_relaxed_read32(csa, TRCSSCSRn(i));
1223 	}
1224 	/* NUMCIDC, bits[27:24] number of Context ID comparators for tracing */
1225 	drvdata->numcidc = BMVAL(etmidr4, 24, 27);
1226 	/* NUMVMIDC, bits[31:28] number of VMID comparators for tracing */
1227 	drvdata->numvmidc = BMVAL(etmidr4, 28, 31);
1228 
1229 	etmidr5 = etm4x_relaxed_read32(csa, TRCIDR5);
1230 	/* NUMEXTIN, bits[8:0] number of external inputs implemented */
1231 	drvdata->nr_ext_inp = BMVAL(etmidr5, 0, 8);
1232 	/* TRACEIDSIZE, bits[21:16] indicates the trace ID width */
1233 	drvdata->trcid_size = BMVAL(etmidr5, 16, 21);
1234 	/* ATBTRIG, bit[22] implementation can support ATB triggers? */
1235 	if (BMVAL(etmidr5, 22, 22))
1236 		drvdata->atbtrig = true;
1237 	else
1238 		drvdata->atbtrig = false;
1239 	/*
1240 	 * LPOVERRIDE, bit[23] implementation supports
1241 	 * low-power state override
1242 	 */
1243 	if (BMVAL(etmidr5, 23, 23) && (!drvdata->skip_power_up))
1244 		drvdata->lpoverride = true;
1245 	else
1246 		drvdata->lpoverride = false;
1247 	/* NUMSEQSTATE, bits[27:25] number of sequencer states implemented */
1248 	drvdata->nrseqstate = BMVAL(etmidr5, 25, 27);
1249 	/* NUMCNTR, bits[30:28] number of counters available for tracing */
1250 	drvdata->nr_cntr = BMVAL(etmidr5, 28, 30);
1251 	etm4_cs_lock(drvdata, csa);
1252 	cpu_detect_trace_filtering(drvdata);
1253 }
1254 
1255 static inline u32 etm4_get_victlr_access_type(struct etmv4_config *config)
1256 {
1257 	return etm4_get_access_type(config) << TRCVICTLR_EXLEVEL_SHIFT;
1258 }
1259 
1260 /* Set ELx trace filter access in the TRCVICTLR register */
1261 static void etm4_set_victlr_access(struct etmv4_config *config)
1262 {
1263 	config->vinst_ctrl &= ~TRCVICTLR_EXLEVEL_MASK;
1264 	config->vinst_ctrl |= etm4_get_victlr_access_type(config);
1265 }
1266 
1267 static void etm4_set_default_config(struct etmv4_config *config)
1268 {
1269 	/* disable all events tracing */
1270 	config->eventctrl0 = 0x0;
1271 	config->eventctrl1 = 0x0;
1272 
1273 	/* disable stalling */
1274 	config->stall_ctrl = 0x0;
1275 
1276 	/* enable trace synchronization every 4096 bytes, if available */
1277 	config->syncfreq = 0xC;
1278 
1279 	/* disable timestamp event */
1280 	config->ts_ctrl = 0x0;
1281 
1282 	/* TRCVICTLR::EVENT = 0x01, select the always on logic */
1283 	config->vinst_ctrl = BIT(0);
1284 
1285 	/* TRCVICTLR::EXLEVEL_NS:EXLEVELS: Set kernel / user filtering */
1286 	etm4_set_victlr_access(config);
1287 }
1288 
1289 static u64 etm4_get_ns_access_type(struct etmv4_config *config)
1290 {
1291 	u64 access_type = 0;
1292 
1293 	/*
1294 	 * EXLEVEL_NS, for NonSecure Exception levels.
1295 	 * The mask here is a generic value and must be
1296 	 * shifted to the corresponding field for the registers
1297 	 */
1298 	if (!is_kernel_in_hyp_mode()) {
1299 		/* Stay away from hypervisor mode for non-VHE */
1300 		access_type =  ETM_EXLEVEL_NS_HYP;
1301 		if (config->mode & ETM_MODE_EXCL_KERN)
1302 			access_type |= ETM_EXLEVEL_NS_OS;
1303 	} else if (config->mode & ETM_MODE_EXCL_KERN) {
1304 		access_type = ETM_EXLEVEL_NS_HYP;
1305 	}
1306 
1307 	if (config->mode & ETM_MODE_EXCL_USER)
1308 		access_type |= ETM_EXLEVEL_NS_APP;
1309 
1310 	return access_type;
1311 }
1312 
1313 /*
1314  * Construct the exception level masks for a given config.
1315  * This must be shifted to the corresponding register field
1316  * for usage.
1317  */
1318 static u64 etm4_get_access_type(struct etmv4_config *config)
1319 {
1320 	/* All Secure exception levels are excluded from the trace */
1321 	return etm4_get_ns_access_type(config) | (u64)config->s_ex_level;
1322 }
1323 
1324 static u64 etm4_get_comparator_access_type(struct etmv4_config *config)
1325 {
1326 	return etm4_get_access_type(config) << TRCACATR_EXLEVEL_SHIFT;
1327 }
1328 
1329 static void etm4_set_comparator_filter(struct etmv4_config *config,
1330 				       u64 start, u64 stop, int comparator)
1331 {
1332 	u64 access_type = etm4_get_comparator_access_type(config);
1333 
1334 	/* First half of default address comparator */
1335 	config->addr_val[comparator] = start;
1336 	config->addr_acc[comparator] = access_type;
1337 	config->addr_type[comparator] = ETM_ADDR_TYPE_RANGE;
1338 
1339 	/* Second half of default address comparator */
1340 	config->addr_val[comparator + 1] = stop;
1341 	config->addr_acc[comparator + 1] = access_type;
1342 	config->addr_type[comparator + 1] = ETM_ADDR_TYPE_RANGE;
1343 
1344 	/*
1345 	 * Configure the ViewInst function to include this address range
1346 	 * comparator.
1347 	 *
1348 	 * @comparator is divided by two since it is the index in the
1349 	 * etmv4_config::addr_val array but register TRCVIIECTLR deals with
1350 	 * address range comparator _pairs_.
1351 	 *
1352 	 * Therefore:
1353 	 *	index 0 -> compatator pair 0
1354 	 *	index 2 -> comparator pair 1
1355 	 *	index 4 -> comparator pair 2
1356 	 *	...
1357 	 *	index 14 -> comparator pair 7
1358 	 */
1359 	config->viiectlr |= BIT(comparator / 2);
1360 }
1361 
1362 static void etm4_set_start_stop_filter(struct etmv4_config *config,
1363 				       u64 address, int comparator,
1364 				       enum etm_addr_type type)
1365 {
1366 	int shift;
1367 	u64 access_type = etm4_get_comparator_access_type(config);
1368 
1369 	/* Configure the comparator */
1370 	config->addr_val[comparator] = address;
1371 	config->addr_acc[comparator] = access_type;
1372 	config->addr_type[comparator] = type;
1373 
1374 	/*
1375 	 * Configure ViewInst Start-Stop control register.
1376 	 * Addresses configured to start tracing go from bit 0 to n-1,
1377 	 * while those configured to stop tracing from 16 to 16 + n-1.
1378 	 */
1379 	shift = (type == ETM_ADDR_TYPE_START ? 0 : 16);
1380 	config->vissctlr |= BIT(shift + comparator);
1381 }
1382 
1383 static void etm4_set_default_filter(struct etmv4_config *config)
1384 {
1385 	/* Trace everything 'default' filter achieved by no filtering */
1386 	config->viiectlr = 0x0;
1387 
1388 	/*
1389 	 * TRCVICTLR::SSSTATUS == 1, the start-stop logic is
1390 	 * in the started state
1391 	 */
1392 	config->vinst_ctrl |= BIT(9);
1393 	config->mode |= ETM_MODE_VIEWINST_STARTSTOP;
1394 
1395 	/* No start-stop filtering for ViewInst */
1396 	config->vissctlr = 0x0;
1397 }
1398 
1399 static void etm4_set_default(struct etmv4_config *config)
1400 {
1401 	if (WARN_ON_ONCE(!config))
1402 		return;
1403 
1404 	/*
1405 	 * Make default initialisation trace everything
1406 	 *
1407 	 * This is done by a minimum default config sufficient to enable
1408 	 * full instruction trace - with a default filter for trace all
1409 	 * achieved by having no filtering.
1410 	 */
1411 	etm4_set_default_config(config);
1412 	etm4_set_default_filter(config);
1413 }
1414 
1415 static int etm4_get_next_comparator(struct etmv4_drvdata *drvdata, u32 type)
1416 {
1417 	int nr_comparator, index = 0;
1418 	struct etmv4_config *config = &drvdata->config;
1419 
1420 	/*
1421 	 * nr_addr_cmp holds the number of comparator _pair_, so time 2
1422 	 * for the total number of comparators.
1423 	 */
1424 	nr_comparator = drvdata->nr_addr_cmp * 2;
1425 
1426 	/* Go through the tally of comparators looking for a free one. */
1427 	while (index < nr_comparator) {
1428 		switch (type) {
1429 		case ETM_ADDR_TYPE_RANGE:
1430 			if (config->addr_type[index] == ETM_ADDR_TYPE_NONE &&
1431 			    config->addr_type[index + 1] == ETM_ADDR_TYPE_NONE)
1432 				return index;
1433 
1434 			/* Address range comparators go in pairs */
1435 			index += 2;
1436 			break;
1437 		case ETM_ADDR_TYPE_START:
1438 		case ETM_ADDR_TYPE_STOP:
1439 			if (config->addr_type[index] == ETM_ADDR_TYPE_NONE)
1440 				return index;
1441 
1442 			/* Start/stop address can have odd indexes */
1443 			index += 1;
1444 			break;
1445 		default:
1446 			return -EINVAL;
1447 		}
1448 	}
1449 
1450 	/* If we are here all the comparators have been used. */
1451 	return -ENOSPC;
1452 }
1453 
1454 static int etm4_set_event_filters(struct etmv4_drvdata *drvdata,
1455 				  struct perf_event *event)
1456 {
1457 	int i, comparator, ret = 0;
1458 	u64 address;
1459 	struct etmv4_config *config = &drvdata->config;
1460 	struct etm_filters *filters = event->hw.addr_filters;
1461 
1462 	if (!filters)
1463 		goto default_filter;
1464 
1465 	/* Sync events with what Perf got */
1466 	perf_event_addr_filters_sync(event);
1467 
1468 	/*
1469 	 * If there are no filters to deal with simply go ahead with
1470 	 * the default filter, i.e the entire address range.
1471 	 */
1472 	if (!filters->nr_filters)
1473 		goto default_filter;
1474 
1475 	for (i = 0; i < filters->nr_filters; i++) {
1476 		struct etm_filter *filter = &filters->etm_filter[i];
1477 		enum etm_addr_type type = filter->type;
1478 
1479 		/* See if a comparator is free. */
1480 		comparator = etm4_get_next_comparator(drvdata, type);
1481 		if (comparator < 0) {
1482 			ret = comparator;
1483 			goto out;
1484 		}
1485 
1486 		switch (type) {
1487 		case ETM_ADDR_TYPE_RANGE:
1488 			etm4_set_comparator_filter(config,
1489 						   filter->start_addr,
1490 						   filter->stop_addr,
1491 						   comparator);
1492 			/*
1493 			 * TRCVICTLR::SSSTATUS == 1, the start-stop logic is
1494 			 * in the started state
1495 			 */
1496 			config->vinst_ctrl |= BIT(9);
1497 
1498 			/* No start-stop filtering for ViewInst */
1499 			config->vissctlr = 0x0;
1500 			break;
1501 		case ETM_ADDR_TYPE_START:
1502 		case ETM_ADDR_TYPE_STOP:
1503 			/* Get the right start or stop address */
1504 			address = (type == ETM_ADDR_TYPE_START ?
1505 				   filter->start_addr :
1506 				   filter->stop_addr);
1507 
1508 			/* Configure comparator */
1509 			etm4_set_start_stop_filter(config, address,
1510 						   comparator, type);
1511 
1512 			/*
1513 			 * If filters::ssstatus == 1, trace acquisition was
1514 			 * started but the process was yanked away before the
1515 			 * the stop address was hit.  As such the start/stop
1516 			 * logic needs to be re-started so that tracing can
1517 			 * resume where it left.
1518 			 *
1519 			 * The start/stop logic status when a process is
1520 			 * scheduled out is checked in function
1521 			 * etm4_disable_perf().
1522 			 */
1523 			if (filters->ssstatus)
1524 				config->vinst_ctrl |= BIT(9);
1525 
1526 			/* No include/exclude filtering for ViewInst */
1527 			config->viiectlr = 0x0;
1528 			break;
1529 		default:
1530 			ret = -EINVAL;
1531 			goto out;
1532 		}
1533 	}
1534 
1535 	goto out;
1536 
1537 
1538 default_filter:
1539 	etm4_set_default_filter(config);
1540 
1541 out:
1542 	return ret;
1543 }
1544 
1545 void etm4_config_trace_mode(struct etmv4_config *config)
1546 {
1547 	u32 mode;
1548 
1549 	mode = config->mode;
1550 	mode &= (ETM_MODE_EXCL_KERN | ETM_MODE_EXCL_USER);
1551 
1552 	/* excluding kernel AND user space doesn't make sense */
1553 	WARN_ON_ONCE(mode == (ETM_MODE_EXCL_KERN | ETM_MODE_EXCL_USER));
1554 
1555 	/* nothing to do if neither flags are set */
1556 	if (!(mode & ETM_MODE_EXCL_KERN) && !(mode & ETM_MODE_EXCL_USER))
1557 		return;
1558 
1559 	etm4_set_victlr_access(config);
1560 }
1561 
1562 static int etm4_online_cpu(unsigned int cpu)
1563 {
1564 	if (!etmdrvdata[cpu])
1565 		return 0;
1566 
1567 	if (etmdrvdata[cpu]->boot_enable && !etmdrvdata[cpu]->sticky_enable)
1568 		coresight_enable(etmdrvdata[cpu]->csdev);
1569 	return 0;
1570 }
1571 
1572 static int etm4_starting_cpu(unsigned int cpu)
1573 {
1574 	if (!etmdrvdata[cpu])
1575 		return 0;
1576 
1577 	spin_lock(&etmdrvdata[cpu]->spinlock);
1578 	if (!etmdrvdata[cpu]->os_unlock)
1579 		etm4_os_unlock(etmdrvdata[cpu]);
1580 
1581 	if (local_read(&etmdrvdata[cpu]->mode))
1582 		etm4_enable_hw(etmdrvdata[cpu]);
1583 	spin_unlock(&etmdrvdata[cpu]->spinlock);
1584 	return 0;
1585 }
1586 
1587 static int etm4_dying_cpu(unsigned int cpu)
1588 {
1589 	if (!etmdrvdata[cpu])
1590 		return 0;
1591 
1592 	spin_lock(&etmdrvdata[cpu]->spinlock);
1593 	if (local_read(&etmdrvdata[cpu]->mode))
1594 		etm4_disable_hw(etmdrvdata[cpu]);
1595 	spin_unlock(&etmdrvdata[cpu]->spinlock);
1596 	return 0;
1597 }
1598 
1599 static void etm4_init_trace_id(struct etmv4_drvdata *drvdata)
1600 {
1601 	drvdata->trcid = coresight_get_trace_id(drvdata->cpu);
1602 }
1603 
1604 static int __etm4_cpu_save(struct etmv4_drvdata *drvdata)
1605 {
1606 	int i, ret = 0;
1607 	struct etmv4_save_state *state;
1608 	struct coresight_device *csdev = drvdata->csdev;
1609 	struct csdev_access *csa;
1610 	struct device *etm_dev;
1611 
1612 	if (WARN_ON(!csdev))
1613 		return -ENODEV;
1614 
1615 	etm_dev = &csdev->dev;
1616 	csa = &csdev->access;
1617 
1618 	/*
1619 	 * As recommended by 3.4.1 ("The procedure when powering down the PE")
1620 	 * of ARM IHI 0064D
1621 	 */
1622 	dsb(sy);
1623 	isb();
1624 
1625 	etm4_cs_unlock(drvdata, csa);
1626 	/* Lock the OS lock to disable trace and external debugger access */
1627 	etm4_os_lock(drvdata);
1628 
1629 	/* wait for TRCSTATR.PMSTABLE to go up */
1630 	if (coresight_timeout(csa, TRCSTATR, TRCSTATR_PMSTABLE_BIT, 1)) {
1631 		dev_err(etm_dev,
1632 			"timeout while waiting for PM Stable Status\n");
1633 		etm4_os_unlock(drvdata);
1634 		ret = -EBUSY;
1635 		goto out;
1636 	}
1637 
1638 	state = drvdata->save_state;
1639 
1640 	state->trcprgctlr = etm4x_read32(csa, TRCPRGCTLR);
1641 	if (drvdata->nr_pe)
1642 		state->trcprocselr = etm4x_read32(csa, TRCPROCSELR);
1643 	state->trcconfigr = etm4x_read32(csa, TRCCONFIGR);
1644 	state->trcauxctlr = etm4x_read32(csa, TRCAUXCTLR);
1645 	state->trceventctl0r = etm4x_read32(csa, TRCEVENTCTL0R);
1646 	state->trceventctl1r = etm4x_read32(csa, TRCEVENTCTL1R);
1647 	if (drvdata->stallctl)
1648 		state->trcstallctlr = etm4x_read32(csa, TRCSTALLCTLR);
1649 	state->trctsctlr = etm4x_read32(csa, TRCTSCTLR);
1650 	state->trcsyncpr = etm4x_read32(csa, TRCSYNCPR);
1651 	state->trcccctlr = etm4x_read32(csa, TRCCCCTLR);
1652 	state->trcbbctlr = etm4x_read32(csa, TRCBBCTLR);
1653 	state->trctraceidr = etm4x_read32(csa, TRCTRACEIDR);
1654 	state->trcqctlr = etm4x_read32(csa, TRCQCTLR);
1655 
1656 	state->trcvictlr = etm4x_read32(csa, TRCVICTLR);
1657 	state->trcviiectlr = etm4x_read32(csa, TRCVIIECTLR);
1658 	state->trcvissctlr = etm4x_read32(csa, TRCVISSCTLR);
1659 	if (drvdata->nr_pe_cmp)
1660 		state->trcvipcssctlr = etm4x_read32(csa, TRCVIPCSSCTLR);
1661 	state->trcvdctlr = etm4x_read32(csa, TRCVDCTLR);
1662 	state->trcvdsacctlr = etm4x_read32(csa, TRCVDSACCTLR);
1663 	state->trcvdarcctlr = etm4x_read32(csa, TRCVDARCCTLR);
1664 
1665 	for (i = 0; i < drvdata->nrseqstate - 1; i++)
1666 		state->trcseqevr[i] = etm4x_read32(csa, TRCSEQEVRn(i));
1667 
1668 	state->trcseqrstevr = etm4x_read32(csa, TRCSEQRSTEVR);
1669 	state->trcseqstr = etm4x_read32(csa, TRCSEQSTR);
1670 	state->trcextinselr = etm4x_read32(csa, TRCEXTINSELR);
1671 
1672 	for (i = 0; i < drvdata->nr_cntr; i++) {
1673 		state->trccntrldvr[i] = etm4x_read32(csa, TRCCNTRLDVRn(i));
1674 		state->trccntctlr[i] = etm4x_read32(csa, TRCCNTCTLRn(i));
1675 		state->trccntvr[i] = etm4x_read32(csa, TRCCNTVRn(i));
1676 	}
1677 
1678 	for (i = 0; i < drvdata->nr_resource * 2; i++)
1679 		state->trcrsctlr[i] = etm4x_read32(csa, TRCRSCTLRn(i));
1680 
1681 	for (i = 0; i < drvdata->nr_ss_cmp; i++) {
1682 		state->trcssccr[i] = etm4x_read32(csa, TRCSSCCRn(i));
1683 		state->trcsscsr[i] = etm4x_read32(csa, TRCSSCSRn(i));
1684 		if (etm4x_sspcicrn_present(drvdata, i))
1685 			state->trcsspcicr[i] = etm4x_read32(csa, TRCSSPCICRn(i));
1686 	}
1687 
1688 	for (i = 0; i < drvdata->nr_addr_cmp * 2; i++) {
1689 		state->trcacvr[i] = etm4x_read64(csa, TRCACVRn(i));
1690 		state->trcacatr[i] = etm4x_read64(csa, TRCACATRn(i));
1691 	}
1692 
1693 	/*
1694 	 * Data trace stream is architecturally prohibited for A profile cores
1695 	 * so we don't save (or later restore) trcdvcvr and trcdvcmr - As per
1696 	 * section 1.3.4 ("Possible functional configurations of an ETMv4 trace
1697 	 * unit") of ARM IHI 0064D.
1698 	 */
1699 
1700 	for (i = 0; i < drvdata->numcidc; i++)
1701 		state->trccidcvr[i] = etm4x_read64(csa, TRCCIDCVRn(i));
1702 
1703 	for (i = 0; i < drvdata->numvmidc; i++)
1704 		state->trcvmidcvr[i] = etm4x_read64(csa, TRCVMIDCVRn(i));
1705 
1706 	state->trccidcctlr0 = etm4x_read32(csa, TRCCIDCCTLR0);
1707 	if (drvdata->numcidc > 4)
1708 		state->trccidcctlr1 = etm4x_read32(csa, TRCCIDCCTLR1);
1709 
1710 	state->trcvmidcctlr0 = etm4x_read32(csa, TRCVMIDCCTLR0);
1711 	if (drvdata->numvmidc > 4)
1712 		state->trcvmidcctlr0 = etm4x_read32(csa, TRCVMIDCCTLR1);
1713 
1714 	state->trcclaimset = etm4x_read32(csa, TRCCLAIMCLR);
1715 
1716 	if (!drvdata->skip_power_up)
1717 		state->trcpdcr = etm4x_read32(csa, TRCPDCR);
1718 
1719 	/* wait for TRCSTATR.IDLE to go up */
1720 	if (coresight_timeout(csa, TRCSTATR, TRCSTATR_IDLE_BIT, 1)) {
1721 		dev_err(etm_dev,
1722 			"timeout while waiting for Idle Trace Status\n");
1723 		etm4_os_unlock(drvdata);
1724 		ret = -EBUSY;
1725 		goto out;
1726 	}
1727 
1728 	drvdata->state_needs_restore = true;
1729 
1730 	/*
1731 	 * Power can be removed from the trace unit now. We do this to
1732 	 * potentially save power on systems that respect the TRCPDCR_PU
1733 	 * despite requesting software to save/restore state.
1734 	 */
1735 	if (!drvdata->skip_power_up)
1736 		etm4x_relaxed_write32(csa, (state->trcpdcr & ~TRCPDCR_PU),
1737 				      TRCPDCR);
1738 out:
1739 	etm4_cs_lock(drvdata, csa);
1740 	return ret;
1741 }
1742 
1743 static int etm4_cpu_save(struct etmv4_drvdata *drvdata)
1744 {
1745 	int ret = 0;
1746 
1747 	/* Save the TRFCR irrespective of whether the ETM is ON */
1748 	if (drvdata->trfcr)
1749 		drvdata->save_trfcr = read_trfcr();
1750 	/*
1751 	 * Save and restore the ETM Trace registers only if
1752 	 * the ETM is active.
1753 	 */
1754 	if (local_read(&drvdata->mode) && drvdata->save_state)
1755 		ret = __etm4_cpu_save(drvdata);
1756 	return ret;
1757 }
1758 
1759 static void __etm4_cpu_restore(struct etmv4_drvdata *drvdata)
1760 {
1761 	int i;
1762 	struct etmv4_save_state *state = drvdata->save_state;
1763 	struct csdev_access tmp_csa = CSDEV_ACCESS_IOMEM(drvdata->base);
1764 	struct csdev_access *csa = &tmp_csa;
1765 
1766 	etm4_cs_unlock(drvdata, csa);
1767 	etm4x_relaxed_write32(csa, state->trcclaimset, TRCCLAIMSET);
1768 
1769 	etm4x_relaxed_write32(csa, state->trcprgctlr, TRCPRGCTLR);
1770 	if (drvdata->nr_pe)
1771 		etm4x_relaxed_write32(csa, state->trcprocselr, TRCPROCSELR);
1772 	etm4x_relaxed_write32(csa, state->trcconfigr, TRCCONFIGR);
1773 	etm4x_relaxed_write32(csa, state->trcauxctlr, TRCAUXCTLR);
1774 	etm4x_relaxed_write32(csa, state->trceventctl0r, TRCEVENTCTL0R);
1775 	etm4x_relaxed_write32(csa, state->trceventctl1r, TRCEVENTCTL1R);
1776 	if (drvdata->stallctl)
1777 		etm4x_relaxed_write32(csa, state->trcstallctlr, TRCSTALLCTLR);
1778 	etm4x_relaxed_write32(csa, state->trctsctlr, TRCTSCTLR);
1779 	etm4x_relaxed_write32(csa, state->trcsyncpr, TRCSYNCPR);
1780 	etm4x_relaxed_write32(csa, state->trcccctlr, TRCCCCTLR);
1781 	etm4x_relaxed_write32(csa, state->trcbbctlr, TRCBBCTLR);
1782 	etm4x_relaxed_write32(csa, state->trctraceidr, TRCTRACEIDR);
1783 	etm4x_relaxed_write32(csa, state->trcqctlr, TRCQCTLR);
1784 
1785 	etm4x_relaxed_write32(csa, state->trcvictlr, TRCVICTLR);
1786 	etm4x_relaxed_write32(csa, state->trcviiectlr, TRCVIIECTLR);
1787 	etm4x_relaxed_write32(csa, state->trcvissctlr, TRCVISSCTLR);
1788 	if (drvdata->nr_pe_cmp)
1789 		etm4x_relaxed_write32(csa, state->trcvipcssctlr, TRCVIPCSSCTLR);
1790 	etm4x_relaxed_write32(csa, state->trcvdctlr, TRCVDCTLR);
1791 	etm4x_relaxed_write32(csa, state->trcvdsacctlr, TRCVDSACCTLR);
1792 	etm4x_relaxed_write32(csa, state->trcvdarcctlr, TRCVDARCCTLR);
1793 
1794 	for (i = 0; i < drvdata->nrseqstate - 1; i++)
1795 		etm4x_relaxed_write32(csa, state->trcseqevr[i], TRCSEQEVRn(i));
1796 
1797 	etm4x_relaxed_write32(csa, state->trcseqrstevr, TRCSEQRSTEVR);
1798 	etm4x_relaxed_write32(csa, state->trcseqstr, TRCSEQSTR);
1799 	etm4x_relaxed_write32(csa, state->trcextinselr, TRCEXTINSELR);
1800 
1801 	for (i = 0; i < drvdata->nr_cntr; i++) {
1802 		etm4x_relaxed_write32(csa, state->trccntrldvr[i], TRCCNTRLDVRn(i));
1803 		etm4x_relaxed_write32(csa, state->trccntctlr[i], TRCCNTCTLRn(i));
1804 		etm4x_relaxed_write32(csa, state->trccntvr[i], TRCCNTVRn(i));
1805 	}
1806 
1807 	for (i = 0; i < drvdata->nr_resource * 2; i++)
1808 		etm4x_relaxed_write32(csa, state->trcrsctlr[i], TRCRSCTLRn(i));
1809 
1810 	for (i = 0; i < drvdata->nr_ss_cmp; i++) {
1811 		etm4x_relaxed_write32(csa, state->trcssccr[i], TRCSSCCRn(i));
1812 		etm4x_relaxed_write32(csa, state->trcsscsr[i], TRCSSCSRn(i));
1813 		if (etm4x_sspcicrn_present(drvdata, i))
1814 			etm4x_relaxed_write32(csa, state->trcsspcicr[i], TRCSSPCICRn(i));
1815 	}
1816 
1817 	for (i = 0; i < drvdata->nr_addr_cmp * 2; i++) {
1818 		etm4x_relaxed_write64(csa, state->trcacvr[i], TRCACVRn(i));
1819 		etm4x_relaxed_write64(csa, state->trcacatr[i], TRCACATRn(i));
1820 	}
1821 
1822 	for (i = 0; i < drvdata->numcidc; i++)
1823 		etm4x_relaxed_write64(csa, state->trccidcvr[i], TRCCIDCVRn(i));
1824 
1825 	for (i = 0; i < drvdata->numvmidc; i++)
1826 		etm4x_relaxed_write64(csa, state->trcvmidcvr[i], TRCVMIDCVRn(i));
1827 
1828 	etm4x_relaxed_write32(csa, state->trccidcctlr0, TRCCIDCCTLR0);
1829 	if (drvdata->numcidc > 4)
1830 		etm4x_relaxed_write32(csa, state->trccidcctlr1, TRCCIDCCTLR1);
1831 
1832 	etm4x_relaxed_write32(csa, state->trcvmidcctlr0, TRCVMIDCCTLR0);
1833 	if (drvdata->numvmidc > 4)
1834 		etm4x_relaxed_write32(csa, state->trcvmidcctlr0, TRCVMIDCCTLR1);
1835 
1836 	etm4x_relaxed_write32(csa, state->trcclaimset, TRCCLAIMSET);
1837 
1838 	if (!drvdata->skip_power_up)
1839 		etm4x_relaxed_write32(csa, state->trcpdcr, TRCPDCR);
1840 
1841 	drvdata->state_needs_restore = false;
1842 
1843 	/*
1844 	 * As recommended by section 4.3.7 ("Synchronization when using the
1845 	 * memory-mapped interface") of ARM IHI 0064D
1846 	 */
1847 	dsb(sy);
1848 	isb();
1849 
1850 	/* Unlock the OS lock to re-enable trace and external debug access */
1851 	etm4_os_unlock(drvdata);
1852 	etm4_cs_lock(drvdata, csa);
1853 }
1854 
1855 static void etm4_cpu_restore(struct etmv4_drvdata *drvdata)
1856 {
1857 	if (drvdata->trfcr)
1858 		write_trfcr(drvdata->save_trfcr);
1859 	if (drvdata->state_needs_restore)
1860 		__etm4_cpu_restore(drvdata);
1861 }
1862 
1863 static int etm4_cpu_pm_notify(struct notifier_block *nb, unsigned long cmd,
1864 			      void *v)
1865 {
1866 	struct etmv4_drvdata *drvdata;
1867 	unsigned int cpu = smp_processor_id();
1868 
1869 	if (!etmdrvdata[cpu])
1870 		return NOTIFY_OK;
1871 
1872 	drvdata = etmdrvdata[cpu];
1873 
1874 	if (WARN_ON_ONCE(drvdata->cpu != cpu))
1875 		return NOTIFY_BAD;
1876 
1877 	switch (cmd) {
1878 	case CPU_PM_ENTER:
1879 		if (etm4_cpu_save(drvdata))
1880 			return NOTIFY_BAD;
1881 		break;
1882 	case CPU_PM_EXIT:
1883 	case CPU_PM_ENTER_FAILED:
1884 		etm4_cpu_restore(drvdata);
1885 		break;
1886 	default:
1887 		return NOTIFY_DONE;
1888 	}
1889 
1890 	return NOTIFY_OK;
1891 }
1892 
1893 static struct notifier_block etm4_cpu_pm_nb = {
1894 	.notifier_call = etm4_cpu_pm_notify,
1895 };
1896 
1897 /* Setup PM. Deals with error conditions and counts */
1898 static int __init etm4_pm_setup(void)
1899 {
1900 	int ret;
1901 
1902 	ret = cpu_pm_register_notifier(&etm4_cpu_pm_nb);
1903 	if (ret)
1904 		return ret;
1905 
1906 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ARM_CORESIGHT_STARTING,
1907 					"arm/coresight4:starting",
1908 					etm4_starting_cpu, etm4_dying_cpu);
1909 
1910 	if (ret)
1911 		goto unregister_notifier;
1912 
1913 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
1914 					"arm/coresight4:online",
1915 					etm4_online_cpu, NULL);
1916 
1917 	/* HP dyn state ID returned in ret on success */
1918 	if (ret > 0) {
1919 		hp_online = ret;
1920 		return 0;
1921 	}
1922 
1923 	/* failed dyn state - remove others */
1924 	cpuhp_remove_state_nocalls(CPUHP_AP_ARM_CORESIGHT_STARTING);
1925 
1926 unregister_notifier:
1927 	cpu_pm_unregister_notifier(&etm4_cpu_pm_nb);
1928 	return ret;
1929 }
1930 
1931 static void etm4_pm_clear(void)
1932 {
1933 	cpu_pm_unregister_notifier(&etm4_cpu_pm_nb);
1934 	cpuhp_remove_state_nocalls(CPUHP_AP_ARM_CORESIGHT_STARTING);
1935 	if (hp_online) {
1936 		cpuhp_remove_state_nocalls(hp_online);
1937 		hp_online = 0;
1938 	}
1939 }
1940 
1941 static int etm4_probe(struct device *dev, void __iomem *base, u32 etm_pid)
1942 {
1943 	int ret;
1944 	struct coresight_platform_data *pdata = NULL;
1945 	struct etmv4_drvdata *drvdata;
1946 	struct coresight_desc desc = { 0 };
1947 	struct etm4_init_arg init_arg = { 0 };
1948 	u8 major, minor;
1949 	char *type_name;
1950 
1951 	drvdata = devm_kzalloc(dev, sizeof(*drvdata), GFP_KERNEL);
1952 	if (!drvdata)
1953 		return -ENOMEM;
1954 
1955 	dev_set_drvdata(dev, drvdata);
1956 
1957 	if (pm_save_enable == PARAM_PM_SAVE_FIRMWARE)
1958 		pm_save_enable = coresight_loses_context_with_cpu(dev) ?
1959 			       PARAM_PM_SAVE_SELF_HOSTED : PARAM_PM_SAVE_NEVER;
1960 
1961 	if (pm_save_enable != PARAM_PM_SAVE_NEVER) {
1962 		drvdata->save_state = devm_kmalloc(dev,
1963 				sizeof(struct etmv4_save_state), GFP_KERNEL);
1964 		if (!drvdata->save_state)
1965 			return -ENOMEM;
1966 	}
1967 
1968 	drvdata->base = base;
1969 
1970 	spin_lock_init(&drvdata->spinlock);
1971 
1972 	drvdata->cpu = coresight_get_cpu(dev);
1973 	if (drvdata->cpu < 0)
1974 		return drvdata->cpu;
1975 
1976 	init_arg.drvdata = drvdata;
1977 	init_arg.csa = &desc.access;
1978 	init_arg.pid = etm_pid;
1979 
1980 	if (smp_call_function_single(drvdata->cpu,
1981 				etm4_init_arch_data,  &init_arg, 1))
1982 		dev_err(dev, "ETM arch init failed\n");
1983 
1984 	if (!drvdata->arch)
1985 		return -EINVAL;
1986 
1987 	/* TRCPDCR is not accessible with system instructions. */
1988 	if (!desc.access.io_mem ||
1989 	    fwnode_property_present(dev_fwnode(dev), "qcom,skip-power-up"))
1990 		drvdata->skip_power_up = true;
1991 
1992 	major = ETM_ARCH_MAJOR_VERSION(drvdata->arch);
1993 	minor = ETM_ARCH_MINOR_VERSION(drvdata->arch);
1994 
1995 	if (etm4x_is_ete(drvdata)) {
1996 		type_name = "ete";
1997 		/* ETE v1 has major version == 0b101. Adjust this for logging.*/
1998 		major -= 4;
1999 	} else {
2000 		type_name = "etm";
2001 	}
2002 
2003 	desc.name = devm_kasprintf(dev, GFP_KERNEL,
2004 				   "%s%d", type_name, drvdata->cpu);
2005 	if (!desc.name)
2006 		return -ENOMEM;
2007 
2008 	etm4_init_trace_id(drvdata);
2009 	etm4_set_default(&drvdata->config);
2010 
2011 	pdata = coresight_get_platform_data(dev);
2012 	if (IS_ERR(pdata))
2013 		return PTR_ERR(pdata);
2014 
2015 	dev->platform_data = pdata;
2016 
2017 	desc.type = CORESIGHT_DEV_TYPE_SOURCE;
2018 	desc.subtype.source_subtype = CORESIGHT_DEV_SUBTYPE_SOURCE_PROC;
2019 	desc.ops = &etm4_cs_ops;
2020 	desc.pdata = pdata;
2021 	desc.dev = dev;
2022 	desc.groups = coresight_etmv4_groups;
2023 	drvdata->csdev = coresight_register(&desc);
2024 	if (IS_ERR(drvdata->csdev))
2025 		return PTR_ERR(drvdata->csdev);
2026 
2027 	ret = etm_perf_symlink(drvdata->csdev, true);
2028 	if (ret) {
2029 		coresight_unregister(drvdata->csdev);
2030 		return ret;
2031 	}
2032 
2033 	/* register with config infrastructure & load any current features */
2034 	ret = etm4_cscfg_register(drvdata->csdev);
2035 	if (ret) {
2036 		coresight_unregister(drvdata->csdev);
2037 		return ret;
2038 	}
2039 
2040 	etmdrvdata[drvdata->cpu] = drvdata;
2041 
2042 	dev_info(&drvdata->csdev->dev, "CPU%d: %s v%d.%d initialized\n",
2043 		 drvdata->cpu, type_name, major, minor);
2044 
2045 	if (boot_enable) {
2046 		coresight_enable(drvdata->csdev);
2047 		drvdata->boot_enable = true;
2048 	}
2049 
2050 	return 0;
2051 }
2052 
2053 static int etm4_probe_amba(struct amba_device *adev, const struct amba_id *id)
2054 {
2055 	void __iomem *base;
2056 	struct device *dev = &adev->dev;
2057 	struct resource *res = &adev->res;
2058 	int ret;
2059 
2060 	/* Validity for the resource is already checked by the AMBA core */
2061 	base = devm_ioremap_resource(dev, res);
2062 	if (IS_ERR(base))
2063 		return PTR_ERR(base);
2064 
2065 	ret = etm4_probe(dev, base, id->id);
2066 	if (!ret)
2067 		pm_runtime_put(&adev->dev);
2068 
2069 	return ret;
2070 }
2071 
2072 static int etm4_probe_platform_dev(struct platform_device *pdev)
2073 {
2074 	int ret;
2075 
2076 	pm_runtime_get_noresume(&pdev->dev);
2077 	pm_runtime_set_active(&pdev->dev);
2078 	pm_runtime_enable(&pdev->dev);
2079 
2080 	/*
2081 	 * System register based devices could match the
2082 	 * HW by reading appropriate registers on the HW
2083 	 * and thus we could skip the PID.
2084 	 */
2085 	ret = etm4_probe(&pdev->dev, NULL, 0);
2086 
2087 	pm_runtime_put(&pdev->dev);
2088 	return ret;
2089 }
2090 
2091 static struct amba_cs_uci_id uci_id_etm4[] = {
2092 	{
2093 		/*  ETMv4 UCI data */
2094 		.devarch	= ETM_DEVARCH_ETMv4x_ARCH,
2095 		.devarch_mask	= ETM_DEVARCH_ID_MASK,
2096 		.devtype	= 0x00000013,
2097 	}
2098 };
2099 
2100 static void clear_etmdrvdata(void *info)
2101 {
2102 	int cpu = *(int *)info;
2103 
2104 	etmdrvdata[cpu] = NULL;
2105 }
2106 
2107 static int __exit etm4_remove_dev(struct etmv4_drvdata *drvdata)
2108 {
2109 	etm_perf_symlink(drvdata->csdev, false);
2110 	/*
2111 	 * Taking hotplug lock here to avoid racing between etm4_remove_dev()
2112 	 * and CPU hotplug call backs.
2113 	 */
2114 	cpus_read_lock();
2115 	/*
2116 	 * The readers for etmdrvdata[] are CPU hotplug call backs
2117 	 * and PM notification call backs. Change etmdrvdata[i] on
2118 	 * CPU i ensures these call backs has consistent view
2119 	 * inside one call back function.
2120 	 */
2121 	if (smp_call_function_single(drvdata->cpu, clear_etmdrvdata, &drvdata->cpu, 1))
2122 		etmdrvdata[drvdata->cpu] = NULL;
2123 
2124 	cpus_read_unlock();
2125 
2126 	cscfg_unregister_csdev(drvdata->csdev);
2127 	coresight_unregister(drvdata->csdev);
2128 
2129 	return 0;
2130 }
2131 
2132 static void __exit etm4_remove_amba(struct amba_device *adev)
2133 {
2134 	struct etmv4_drvdata *drvdata = dev_get_drvdata(&adev->dev);
2135 
2136 	if (drvdata)
2137 		etm4_remove_dev(drvdata);
2138 }
2139 
2140 static int __exit etm4_remove_platform_dev(struct platform_device *pdev)
2141 {
2142 	int ret = 0;
2143 	struct etmv4_drvdata *drvdata = dev_get_drvdata(&pdev->dev);
2144 
2145 	if (drvdata)
2146 		ret = etm4_remove_dev(drvdata);
2147 	pm_runtime_disable(&pdev->dev);
2148 	return ret;
2149 }
2150 
2151 static const struct amba_id etm4_ids[] = {
2152 	CS_AMBA_ID(0x000bb95d),			/* Cortex-A53 */
2153 	CS_AMBA_ID(0x000bb95e),			/* Cortex-A57 */
2154 	CS_AMBA_ID(0x000bb95a),			/* Cortex-A72 */
2155 	CS_AMBA_ID(0x000bb959),			/* Cortex-A73 */
2156 	CS_AMBA_UCI_ID(0x000bb9da, uci_id_etm4),/* Cortex-A35 */
2157 	CS_AMBA_UCI_ID(0x000bbd05, uci_id_etm4),/* Cortex-A55 */
2158 	CS_AMBA_UCI_ID(0x000bbd0a, uci_id_etm4),/* Cortex-A75 */
2159 	CS_AMBA_UCI_ID(0x000bbd0c, uci_id_etm4),/* Neoverse N1 */
2160 	CS_AMBA_UCI_ID(0x000bbd41, uci_id_etm4),/* Cortex-A78 */
2161 	CS_AMBA_UCI_ID(0x000f0205, uci_id_etm4),/* Qualcomm Kryo */
2162 	CS_AMBA_UCI_ID(0x000f0211, uci_id_etm4),/* Qualcomm Kryo */
2163 	CS_AMBA_UCI_ID(0x000bb802, uci_id_etm4),/* Qualcomm Kryo 385 Cortex-A55 */
2164 	CS_AMBA_UCI_ID(0x000bb803, uci_id_etm4),/* Qualcomm Kryo 385 Cortex-A75 */
2165 	CS_AMBA_UCI_ID(0x000bb805, uci_id_etm4),/* Qualcomm Kryo 4XX Cortex-A55 */
2166 	CS_AMBA_UCI_ID(0x000bb804, uci_id_etm4),/* Qualcomm Kryo 4XX Cortex-A76 */
2167 	CS_AMBA_UCI_ID(0x000bbd0d, uci_id_etm4),/* Qualcomm Kryo 5XX Cortex-A77 */
2168 	CS_AMBA_UCI_ID(0x000cc0af, uci_id_etm4),/* Marvell ThunderX2 */
2169 	CS_AMBA_UCI_ID(0x000b6d01, uci_id_etm4),/* HiSilicon-Hip08 */
2170 	CS_AMBA_UCI_ID(0x000b6d02, uci_id_etm4),/* HiSilicon-Hip09 */
2171 	{},
2172 };
2173 
2174 MODULE_DEVICE_TABLE(amba, etm4_ids);
2175 
2176 static struct amba_driver etm4x_amba_driver = {
2177 	.drv = {
2178 		.name   = "coresight-etm4x",
2179 		.owner  = THIS_MODULE,
2180 		.suppress_bind_attrs = true,
2181 	},
2182 	.probe		= etm4_probe_amba,
2183 	.remove         = etm4_remove_amba,
2184 	.id_table	= etm4_ids,
2185 };
2186 
2187 static const struct of_device_id etm4_sysreg_match[] = {
2188 	{ .compatible	= "arm,coresight-etm4x-sysreg" },
2189 	{ .compatible	= "arm,embedded-trace-extension" },
2190 	{}
2191 };
2192 
2193 static struct platform_driver etm4_platform_driver = {
2194 	.probe		= etm4_probe_platform_dev,
2195 	.remove		= etm4_remove_platform_dev,
2196 	.driver			= {
2197 		.name			= "coresight-etm4x",
2198 		.of_match_table		= etm4_sysreg_match,
2199 		.suppress_bind_attrs	= true,
2200 	},
2201 };
2202 
2203 static int __init etm4x_init(void)
2204 {
2205 	int ret;
2206 
2207 	ret = etm4_pm_setup();
2208 
2209 	/* etm4_pm_setup() does its own cleanup - exit on error */
2210 	if (ret)
2211 		return ret;
2212 
2213 	ret = amba_driver_register(&etm4x_amba_driver);
2214 	if (ret) {
2215 		pr_err("Error registering etm4x AMBA driver\n");
2216 		goto clear_pm;
2217 	}
2218 
2219 	ret = platform_driver_register(&etm4_platform_driver);
2220 	if (!ret)
2221 		return 0;
2222 
2223 	pr_err("Error registering etm4x platform driver\n");
2224 	amba_driver_unregister(&etm4x_amba_driver);
2225 
2226 clear_pm:
2227 	etm4_pm_clear();
2228 	return ret;
2229 }
2230 
2231 static void __exit etm4x_exit(void)
2232 {
2233 	amba_driver_unregister(&etm4x_amba_driver);
2234 	platform_driver_unregister(&etm4_platform_driver);
2235 	etm4_pm_clear();
2236 }
2237 
2238 module_init(etm4x_init);
2239 module_exit(etm4x_exit);
2240 
2241 MODULE_AUTHOR("Pratik Patel <pratikp@codeaurora.org>");
2242 MODULE_AUTHOR("Mathieu Poirier <mathieu.poirier@linaro.org>");
2243 MODULE_DESCRIPTION("Arm CoreSight Program Flow Trace v4.x driver");
2244 MODULE_LICENSE("GPL v2");
2245