1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2012, The Linux Foundation. All rights reserved.
4  */
5 
6 #include <linux/build_bug.h>
7 #include <linux/kernel.h>
8 #include <linux/init.h>
9 #include <linux/types.h>
10 #include <linux/device.h>
11 #include <linux/io.h>
12 #include <linux/idr.h>
13 #include <linux/err.h>
14 #include <linux/export.h>
15 #include <linux/slab.h>
16 #include <linux/stringhash.h>
17 #include <linux/mutex.h>
18 #include <linux/clk.h>
19 #include <linux/coresight.h>
20 #include <linux/of_platform.h>
21 #include <linux/delay.h>
22 #include <linux/pm_runtime.h>
23 
24 #include "coresight-etm-perf.h"
25 #include "coresight-priv.h"
26 #include "coresight-syscfg.h"
27 
28 static DEFINE_MUTEX(coresight_mutex);
29 static DEFINE_PER_CPU(struct coresight_device *, csdev_sink);
30 
31 /*
32  * Use IDR to map the hash of the source's device name
33  * to the pointer of path for the source. The idr is for
34  * the sources which aren't associated with CPU.
35  */
36 static DEFINE_IDR(path_idr);
37 
38 /**
39  * struct coresight_node - elements of a path, from source to sink
40  * @csdev:	Address of an element.
41  * @link:	hook to the list.
42  */
43 struct coresight_node {
44 	struct coresight_device *csdev;
45 	struct list_head link;
46 };
47 
48 /*
49  * When operating Coresight drivers from the sysFS interface, only a single
50  * path can exist from a tracer (associated to a CPU) to a sink.
51  */
52 static DEFINE_PER_CPU(struct list_head *, tracer_path);
53 
54 /*
55  * When losing synchronisation a new barrier packet needs to be inserted at the
56  * beginning of the data collected in a buffer.  That way the decoder knows that
57  * it needs to look for another sync sequence.
58  */
59 const u32 coresight_barrier_pkt[4] = {0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff};
60 EXPORT_SYMBOL_GPL(coresight_barrier_pkt);
61 
62 static const struct cti_assoc_op *cti_assoc_ops;
63 
64 ssize_t coresight_simple_show_pair(struct device *_dev,
65 			      struct device_attribute *attr, char *buf)
66 {
67 	struct coresight_device *csdev = container_of(_dev, struct coresight_device, dev);
68 	struct cs_pair_attribute *cs_attr = container_of(attr, struct cs_pair_attribute, attr);
69 	u64 val;
70 
71 	pm_runtime_get_sync(_dev->parent);
72 	val = csdev_access_relaxed_read_pair(&csdev->access, cs_attr->lo_off, cs_attr->hi_off);
73 	pm_runtime_put_sync(_dev->parent);
74 	return sysfs_emit(buf, "0x%llx\n", val);
75 }
76 EXPORT_SYMBOL_GPL(coresight_simple_show_pair);
77 
78 ssize_t coresight_simple_show32(struct device *_dev,
79 			      struct device_attribute *attr, char *buf)
80 {
81 	struct coresight_device *csdev = container_of(_dev, struct coresight_device, dev);
82 	struct cs_off_attribute *cs_attr = container_of(attr, struct cs_off_attribute, attr);
83 	u64 val;
84 
85 	pm_runtime_get_sync(_dev->parent);
86 	val = csdev_access_relaxed_read32(&csdev->access, cs_attr->off);
87 	pm_runtime_put_sync(_dev->parent);
88 	return sysfs_emit(buf, "0x%llx\n", val);
89 }
90 EXPORT_SYMBOL_GPL(coresight_simple_show32);
91 
92 void coresight_set_cti_ops(const struct cti_assoc_op *cti_op)
93 {
94 	cti_assoc_ops = cti_op;
95 }
96 EXPORT_SYMBOL_GPL(coresight_set_cti_ops);
97 
98 void coresight_remove_cti_ops(void)
99 {
100 	cti_assoc_ops = NULL;
101 }
102 EXPORT_SYMBOL_GPL(coresight_remove_cti_ops);
103 
104 void coresight_set_percpu_sink(int cpu, struct coresight_device *csdev)
105 {
106 	per_cpu(csdev_sink, cpu) = csdev;
107 }
108 EXPORT_SYMBOL_GPL(coresight_set_percpu_sink);
109 
110 struct coresight_device *coresight_get_percpu_sink(int cpu)
111 {
112 	return per_cpu(csdev_sink, cpu);
113 }
114 EXPORT_SYMBOL_GPL(coresight_get_percpu_sink);
115 
116 static struct coresight_connection *
117 coresight_find_out_connection(struct coresight_device *src_dev,
118 			      struct coresight_device *dest_dev)
119 {
120 	int i;
121 	struct coresight_connection *conn;
122 
123 	for (i = 0; i < src_dev->pdata->nr_outconns; i++) {
124 		conn = src_dev->pdata->out_conns[i];
125 		if (conn->dest_dev == dest_dev)
126 			return conn;
127 	}
128 
129 	dev_err(&src_dev->dev,
130 		"couldn't find output connection, src_dev: %s, dest_dev: %s\n",
131 		dev_name(&src_dev->dev), dev_name(&dest_dev->dev));
132 
133 	return ERR_PTR(-ENODEV);
134 }
135 
136 static inline u32 coresight_read_claim_tags(struct coresight_device *csdev)
137 {
138 	return csdev_access_relaxed_read32(&csdev->access, CORESIGHT_CLAIMCLR);
139 }
140 
141 static inline bool coresight_is_claimed_self_hosted(struct coresight_device *csdev)
142 {
143 	return coresight_read_claim_tags(csdev) == CORESIGHT_CLAIM_SELF_HOSTED;
144 }
145 
146 static inline bool coresight_is_claimed_any(struct coresight_device *csdev)
147 {
148 	return coresight_read_claim_tags(csdev) != 0;
149 }
150 
151 static inline void coresight_set_claim_tags(struct coresight_device *csdev)
152 {
153 	csdev_access_relaxed_write32(&csdev->access, CORESIGHT_CLAIM_SELF_HOSTED,
154 				     CORESIGHT_CLAIMSET);
155 	isb();
156 }
157 
158 static inline void coresight_clear_claim_tags(struct coresight_device *csdev)
159 {
160 	csdev_access_relaxed_write32(&csdev->access, CORESIGHT_CLAIM_SELF_HOSTED,
161 				     CORESIGHT_CLAIMCLR);
162 	isb();
163 }
164 
165 /*
166  * coresight_claim_device_unlocked : Claim the device for self-hosted usage
167  * to prevent an external tool from touching this device. As per PSCI
168  * standards, section "Preserving the execution context" => "Debug and Trace
169  * save and Restore", DBGCLAIM[1] is reserved for Self-hosted debug/trace and
170  * DBGCLAIM[0] is reserved for external tools.
171  *
172  * Called with CS_UNLOCKed for the component.
173  * Returns : 0 on success
174  */
175 int coresight_claim_device_unlocked(struct coresight_device *csdev)
176 {
177 	if (WARN_ON(!csdev))
178 		return -EINVAL;
179 
180 	if (coresight_is_claimed_any(csdev))
181 		return -EBUSY;
182 
183 	coresight_set_claim_tags(csdev);
184 	if (coresight_is_claimed_self_hosted(csdev))
185 		return 0;
186 	/* There was a race setting the tags, clean up and fail */
187 	coresight_clear_claim_tags(csdev);
188 	return -EBUSY;
189 }
190 EXPORT_SYMBOL_GPL(coresight_claim_device_unlocked);
191 
192 int coresight_claim_device(struct coresight_device *csdev)
193 {
194 	int rc;
195 
196 	if (WARN_ON(!csdev))
197 		return -EINVAL;
198 
199 	CS_UNLOCK(csdev->access.base);
200 	rc = coresight_claim_device_unlocked(csdev);
201 	CS_LOCK(csdev->access.base);
202 
203 	return rc;
204 }
205 EXPORT_SYMBOL_GPL(coresight_claim_device);
206 
207 /*
208  * coresight_disclaim_device_unlocked : Clear the claim tags for the device.
209  * Called with CS_UNLOCKed for the component.
210  */
211 void coresight_disclaim_device_unlocked(struct coresight_device *csdev)
212 {
213 
214 	if (WARN_ON(!csdev))
215 		return;
216 
217 	if (coresight_is_claimed_self_hosted(csdev))
218 		coresight_clear_claim_tags(csdev);
219 	else
220 		/*
221 		 * The external agent may have not honoured our claim
222 		 * and has manipulated it. Or something else has seriously
223 		 * gone wrong in our driver.
224 		 */
225 		WARN_ON_ONCE(1);
226 }
227 EXPORT_SYMBOL_GPL(coresight_disclaim_device_unlocked);
228 
229 void coresight_disclaim_device(struct coresight_device *csdev)
230 {
231 	if (WARN_ON(!csdev))
232 		return;
233 
234 	CS_UNLOCK(csdev->access.base);
235 	coresight_disclaim_device_unlocked(csdev);
236 	CS_LOCK(csdev->access.base);
237 }
238 EXPORT_SYMBOL_GPL(coresight_disclaim_device);
239 
240 /*
241  * Add a helper as an output device. This function takes the @coresight_mutex
242  * because it's assumed that it's called from the helper device, outside of the
243  * core code where the mutex would already be held. Don't add new calls to this
244  * from inside the core code, instead try to add the new helper to the DT and
245  * ACPI where it will be picked up and linked automatically.
246  */
247 void coresight_add_helper(struct coresight_device *csdev,
248 			  struct coresight_device *helper)
249 {
250 	int i;
251 	struct coresight_connection conn = {};
252 	struct coresight_connection *new_conn;
253 
254 	mutex_lock(&coresight_mutex);
255 	conn.dest_fwnode = fwnode_handle_get(dev_fwnode(&helper->dev));
256 	conn.dest_dev = helper;
257 	conn.dest_port = conn.src_port = -1;
258 	conn.src_dev = csdev;
259 
260 	/*
261 	 * Check for duplicates because this is called every time a helper
262 	 * device is re-loaded. Existing connections will get re-linked
263 	 * automatically.
264 	 */
265 	for (i = 0; i < csdev->pdata->nr_outconns; ++i)
266 		if (csdev->pdata->out_conns[i]->dest_fwnode == conn.dest_fwnode)
267 			goto unlock;
268 
269 	new_conn = coresight_add_out_conn(csdev->dev.parent, csdev->pdata,
270 					  &conn);
271 	if (!IS_ERR(new_conn))
272 		coresight_add_in_conn(new_conn);
273 
274 unlock:
275 	mutex_unlock(&coresight_mutex);
276 }
277 EXPORT_SYMBOL_GPL(coresight_add_helper);
278 
279 static int coresight_enable_sink(struct coresight_device *csdev,
280 				 enum cs_mode mode, void *data)
281 {
282 	int ret;
283 
284 	/*
285 	 * We need to make sure the "new" session is compatible with the
286 	 * existing "mode" of operation.
287 	 */
288 	if (!sink_ops(csdev)->enable)
289 		return -EINVAL;
290 
291 	ret = sink_ops(csdev)->enable(csdev, mode, data);
292 	if (ret)
293 		return ret;
294 
295 	csdev->enable = true;
296 
297 	return 0;
298 }
299 
300 static void coresight_disable_sink(struct coresight_device *csdev)
301 {
302 	int ret;
303 
304 	if (!sink_ops(csdev)->disable)
305 		return;
306 
307 	ret = sink_ops(csdev)->disable(csdev);
308 	if (ret)
309 		return;
310 	csdev->enable = false;
311 }
312 
313 static int coresight_enable_link(struct coresight_device *csdev,
314 				 struct coresight_device *parent,
315 				 struct coresight_device *child)
316 {
317 	int ret = 0;
318 	int link_subtype;
319 	struct coresight_connection *inconn, *outconn;
320 
321 	if (!parent || !child)
322 		return -EINVAL;
323 
324 	inconn = coresight_find_out_connection(parent, csdev);
325 	outconn = coresight_find_out_connection(csdev, child);
326 	link_subtype = csdev->subtype.link_subtype;
327 
328 	if (link_subtype == CORESIGHT_DEV_SUBTYPE_LINK_MERG && IS_ERR(inconn))
329 		return PTR_ERR(inconn);
330 	if (link_subtype == CORESIGHT_DEV_SUBTYPE_LINK_SPLIT && IS_ERR(outconn))
331 		return PTR_ERR(outconn);
332 
333 	if (link_ops(csdev)->enable) {
334 		ret = link_ops(csdev)->enable(csdev, inconn, outconn);
335 		if (!ret)
336 			csdev->enable = true;
337 	}
338 
339 	return ret;
340 }
341 
342 static void coresight_disable_link(struct coresight_device *csdev,
343 				   struct coresight_device *parent,
344 				   struct coresight_device *child)
345 {
346 	int i;
347 	int link_subtype;
348 	struct coresight_connection *inconn, *outconn;
349 
350 	if (!parent || !child)
351 		return;
352 
353 	inconn = coresight_find_out_connection(parent, csdev);
354 	outconn = coresight_find_out_connection(csdev, child);
355 	link_subtype = csdev->subtype.link_subtype;
356 
357 	if (link_ops(csdev)->disable) {
358 		link_ops(csdev)->disable(csdev, inconn, outconn);
359 	}
360 
361 	if (link_subtype == CORESIGHT_DEV_SUBTYPE_LINK_MERG) {
362 		for (i = 0; i < csdev->pdata->nr_inconns; i++)
363 			if (atomic_read(&csdev->pdata->in_conns[i]->dest_refcnt) !=
364 			    0)
365 				return;
366 	} else if (link_subtype == CORESIGHT_DEV_SUBTYPE_LINK_SPLIT) {
367 		for (i = 0; i < csdev->pdata->nr_outconns; i++)
368 			if (atomic_read(&csdev->pdata->out_conns[i]->src_refcnt) !=
369 			    0)
370 				return;
371 	} else {
372 		if (atomic_read(&csdev->refcnt) != 0)
373 			return;
374 	}
375 
376 	csdev->enable = false;
377 }
378 
379 int coresight_enable_source(struct coresight_device *csdev, enum cs_mode mode,
380 			    void *data)
381 {
382 	int ret;
383 
384 	if (!csdev->enable) {
385 		if (source_ops(csdev)->enable) {
386 			ret = source_ops(csdev)->enable(csdev, data, mode);
387 			if (ret)
388 				return ret;
389 		}
390 		csdev->enable = true;
391 	}
392 
393 	atomic_inc(&csdev->refcnt);
394 
395 	return 0;
396 }
397 EXPORT_SYMBOL_GPL(coresight_enable_source);
398 
399 static bool coresight_is_helper(struct coresight_device *csdev)
400 {
401 	return csdev->type == CORESIGHT_DEV_TYPE_HELPER;
402 }
403 
404 static int coresight_enable_helper(struct coresight_device *csdev,
405 				   enum cs_mode mode, void *data)
406 {
407 	int ret;
408 
409 	if (!helper_ops(csdev)->enable)
410 		return 0;
411 	ret = helper_ops(csdev)->enable(csdev, mode, data);
412 	if (ret)
413 		return ret;
414 
415 	csdev->enable = true;
416 	return 0;
417 }
418 
419 static void coresight_disable_helper(struct coresight_device *csdev)
420 {
421 	int ret;
422 
423 	if (!helper_ops(csdev)->disable)
424 		return;
425 
426 	ret = helper_ops(csdev)->disable(csdev, NULL);
427 	if (ret)
428 		return;
429 	csdev->enable = false;
430 }
431 
432 static void coresight_disable_helpers(struct coresight_device *csdev)
433 {
434 	int i;
435 	struct coresight_device *helper;
436 
437 	for (i = 0; i < csdev->pdata->nr_outconns; ++i) {
438 		helper = csdev->pdata->out_conns[i]->dest_dev;
439 		if (helper && coresight_is_helper(helper))
440 			coresight_disable_helper(helper);
441 	}
442 }
443 
444 /**
445  *  coresight_disable_source - Drop the reference count by 1 and disable
446  *  the device if there are no users left.
447  *
448  *  @csdev: The coresight device to disable
449  *  @data: Opaque data to pass on to the disable function of the source device.
450  *         For example in perf mode this is a pointer to the struct perf_event.
451  *
452  *  Returns true if the device has been disabled.
453  */
454 bool coresight_disable_source(struct coresight_device *csdev, void *data)
455 {
456 	if (atomic_dec_return(&csdev->refcnt) == 0) {
457 		if (source_ops(csdev)->disable)
458 			source_ops(csdev)->disable(csdev, data);
459 		coresight_disable_helpers(csdev);
460 		csdev->enable = false;
461 	}
462 	return !csdev->enable;
463 }
464 EXPORT_SYMBOL_GPL(coresight_disable_source);
465 
466 /*
467  * coresight_disable_path_from : Disable components in the given path beyond
468  * @nd in the list. If @nd is NULL, all the components, except the SOURCE are
469  * disabled.
470  */
471 static void coresight_disable_path_from(struct list_head *path,
472 					struct coresight_node *nd)
473 {
474 	u32 type;
475 	struct coresight_device *csdev, *parent, *child;
476 
477 	if (!nd)
478 		nd = list_first_entry(path, struct coresight_node, link);
479 
480 	list_for_each_entry_continue(nd, path, link) {
481 		csdev = nd->csdev;
482 		type = csdev->type;
483 
484 		/*
485 		 * ETF devices are tricky... They can be a link or a sink,
486 		 * depending on how they are configured.  If an ETF has been
487 		 * "activated" it will be configured as a sink, otherwise
488 		 * go ahead with the link configuration.
489 		 */
490 		if (type == CORESIGHT_DEV_TYPE_LINKSINK)
491 			type = (csdev == coresight_get_sink(path)) ?
492 						CORESIGHT_DEV_TYPE_SINK :
493 						CORESIGHT_DEV_TYPE_LINK;
494 
495 		switch (type) {
496 		case CORESIGHT_DEV_TYPE_SINK:
497 			coresight_disable_sink(csdev);
498 			break;
499 		case CORESIGHT_DEV_TYPE_SOURCE:
500 			/*
501 			 * We skip the first node in the path assuming that it
502 			 * is the source. So we don't expect a source device in
503 			 * the middle of a path.
504 			 */
505 			WARN_ON(1);
506 			break;
507 		case CORESIGHT_DEV_TYPE_LINK:
508 			parent = list_prev_entry(nd, link)->csdev;
509 			child = list_next_entry(nd, link)->csdev;
510 			coresight_disable_link(csdev, parent, child);
511 			break;
512 		default:
513 			break;
514 		}
515 
516 		/* Disable all helpers adjacent along the path last */
517 		coresight_disable_helpers(csdev);
518 	}
519 }
520 
521 void coresight_disable_path(struct list_head *path)
522 {
523 	coresight_disable_path_from(path, NULL);
524 }
525 EXPORT_SYMBOL_GPL(coresight_disable_path);
526 
527 static int coresight_enable_helpers(struct coresight_device *csdev,
528 				    enum cs_mode mode, void *data)
529 {
530 	int i, ret = 0;
531 	struct coresight_device *helper;
532 
533 	for (i = 0; i < csdev->pdata->nr_outconns; ++i) {
534 		helper = csdev->pdata->out_conns[i]->dest_dev;
535 		if (!helper || !coresight_is_helper(helper))
536 			continue;
537 
538 		ret = coresight_enable_helper(helper, mode, data);
539 		if (ret)
540 			return ret;
541 	}
542 
543 	return 0;
544 }
545 
546 int coresight_enable_path(struct list_head *path, enum cs_mode mode,
547 			  void *sink_data)
548 {
549 	int ret = 0;
550 	u32 type;
551 	struct coresight_node *nd;
552 	struct coresight_device *csdev, *parent, *child;
553 
554 	list_for_each_entry_reverse(nd, path, link) {
555 		csdev = nd->csdev;
556 		type = csdev->type;
557 
558 		/* Enable all helpers adjacent to the path first */
559 		ret = coresight_enable_helpers(csdev, mode, sink_data);
560 		if (ret)
561 			goto err;
562 		/*
563 		 * ETF devices are tricky... They can be a link or a sink,
564 		 * depending on how they are configured.  If an ETF has been
565 		 * "activated" it will be configured as a sink, otherwise
566 		 * go ahead with the link configuration.
567 		 */
568 		if (type == CORESIGHT_DEV_TYPE_LINKSINK)
569 			type = (csdev == coresight_get_sink(path)) ?
570 						CORESIGHT_DEV_TYPE_SINK :
571 						CORESIGHT_DEV_TYPE_LINK;
572 
573 		switch (type) {
574 		case CORESIGHT_DEV_TYPE_SINK:
575 			ret = coresight_enable_sink(csdev, mode, sink_data);
576 			/*
577 			 * Sink is the first component turned on. If we
578 			 * failed to enable the sink, there are no components
579 			 * that need disabling. Disabling the path here
580 			 * would mean we could disrupt an existing session.
581 			 */
582 			if (ret)
583 				goto out;
584 			break;
585 		case CORESIGHT_DEV_TYPE_SOURCE:
586 			/* sources are enabled from either sysFS or Perf */
587 			break;
588 		case CORESIGHT_DEV_TYPE_LINK:
589 			parent = list_prev_entry(nd, link)->csdev;
590 			child = list_next_entry(nd, link)->csdev;
591 			ret = coresight_enable_link(csdev, parent, child);
592 			if (ret)
593 				goto err;
594 			break;
595 		default:
596 			goto err;
597 		}
598 	}
599 
600 out:
601 	return ret;
602 err:
603 	coresight_disable_path_from(path, nd);
604 	goto out;
605 }
606 
607 struct coresight_device *coresight_get_sink(struct list_head *path)
608 {
609 	struct coresight_device *csdev;
610 
611 	if (!path)
612 		return NULL;
613 
614 	csdev = list_last_entry(path, struct coresight_node, link)->csdev;
615 	if (csdev->type != CORESIGHT_DEV_TYPE_SINK &&
616 	    csdev->type != CORESIGHT_DEV_TYPE_LINKSINK)
617 		return NULL;
618 
619 	return csdev;
620 }
621 
622 static struct coresight_device *
623 coresight_find_enabled_sink(struct coresight_device *csdev)
624 {
625 	int i;
626 	struct coresight_device *sink = NULL;
627 
628 	if ((csdev->type == CORESIGHT_DEV_TYPE_SINK ||
629 	     csdev->type == CORESIGHT_DEV_TYPE_LINKSINK) &&
630 	     csdev->activated)
631 		return csdev;
632 
633 	/*
634 	 * Recursively explore each port found on this element.
635 	 */
636 	for (i = 0; i < csdev->pdata->nr_outconns; i++) {
637 		struct coresight_device *child_dev;
638 
639 		child_dev = csdev->pdata->out_conns[i]->dest_dev;
640 		if (child_dev)
641 			sink = coresight_find_enabled_sink(child_dev);
642 		if (sink)
643 			return sink;
644 	}
645 
646 	return NULL;
647 }
648 
649 /**
650  * coresight_get_enabled_sink - returns the first enabled sink using
651  * connection based search starting from the source reference
652  *
653  * @source: Coresight source device reference
654  */
655 struct coresight_device *
656 coresight_get_enabled_sink(struct coresight_device *source)
657 {
658 	if (!source)
659 		return NULL;
660 
661 	return coresight_find_enabled_sink(source);
662 }
663 
664 static int coresight_sink_by_id(struct device *dev, const void *data)
665 {
666 	struct coresight_device *csdev = to_coresight_device(dev);
667 	unsigned long hash;
668 
669 	if (csdev->type == CORESIGHT_DEV_TYPE_SINK ||
670 	     csdev->type == CORESIGHT_DEV_TYPE_LINKSINK) {
671 
672 		if (!csdev->ea)
673 			return 0;
674 		/*
675 		 * See function etm_perf_add_symlink_sink() to know where
676 		 * this comes from.
677 		 */
678 		hash = (unsigned long)csdev->ea->var;
679 
680 		if ((u32)hash == *(u32 *)data)
681 			return 1;
682 	}
683 
684 	return 0;
685 }
686 
687 /**
688  * coresight_get_sink_by_id - returns the sink that matches the id
689  * @id: Id of the sink to match
690  *
691  * The name of a sink is unique, whether it is found on the AMBA bus or
692  * otherwise.  As such the hash of that name can easily be used to identify
693  * a sink.
694  */
695 struct coresight_device *coresight_get_sink_by_id(u32 id)
696 {
697 	struct device *dev = NULL;
698 
699 	dev = bus_find_device(&coresight_bustype, NULL, &id,
700 			      coresight_sink_by_id);
701 
702 	return dev ? to_coresight_device(dev) : NULL;
703 }
704 
705 /**
706  * coresight_get_ref- Helper function to increase reference count to module
707  * and device.
708  *
709  * @csdev: The coresight device to get a reference on.
710  *
711  * Return true in successful case and power up the device.
712  * Return false when failed to get reference of module.
713  */
714 static inline bool coresight_get_ref(struct coresight_device *csdev)
715 {
716 	struct device *dev = csdev->dev.parent;
717 
718 	/* Make sure the driver can't be removed */
719 	if (!try_module_get(dev->driver->owner))
720 		return false;
721 	/* Make sure the device can't go away */
722 	get_device(dev);
723 	pm_runtime_get_sync(dev);
724 	return true;
725 }
726 
727 /**
728  * coresight_put_ref- Helper function to decrease reference count to module
729  * and device. Power off the device.
730  *
731  * @csdev: The coresight device to decrement a reference from.
732  */
733 static inline void coresight_put_ref(struct coresight_device *csdev)
734 {
735 	struct device *dev = csdev->dev.parent;
736 
737 	pm_runtime_put(dev);
738 	put_device(dev);
739 	module_put(dev->driver->owner);
740 }
741 
742 /*
743  * coresight_grab_device - Power up this device and any of the helper
744  * devices connected to it for trace operation. Since the helper devices
745  * don't appear on the trace path, they should be handled along with the
746  * master device.
747  */
748 static int coresight_grab_device(struct coresight_device *csdev)
749 {
750 	int i;
751 
752 	for (i = 0; i < csdev->pdata->nr_outconns; i++) {
753 		struct coresight_device *child;
754 
755 		child = csdev->pdata->out_conns[i]->dest_dev;
756 		if (child && coresight_is_helper(child))
757 			if (!coresight_get_ref(child))
758 				goto err;
759 	}
760 	if (coresight_get_ref(csdev))
761 		return 0;
762 err:
763 	for (i--; i >= 0; i--) {
764 		struct coresight_device *child;
765 
766 		child = csdev->pdata->out_conns[i]->dest_dev;
767 		if (child && coresight_is_helper(child))
768 			coresight_put_ref(child);
769 	}
770 	return -ENODEV;
771 }
772 
773 /*
774  * coresight_drop_device - Release this device and any of the helper
775  * devices connected to it.
776  */
777 static void coresight_drop_device(struct coresight_device *csdev)
778 {
779 	int i;
780 
781 	coresight_put_ref(csdev);
782 	for (i = 0; i < csdev->pdata->nr_outconns; i++) {
783 		struct coresight_device *child;
784 
785 		child = csdev->pdata->out_conns[i]->dest_dev;
786 		if (child && coresight_is_helper(child))
787 			coresight_put_ref(child);
788 	}
789 }
790 
791 /**
792  * _coresight_build_path - recursively build a path from a @csdev to a sink.
793  * @csdev:	The device to start from.
794  * @sink:	The final sink we want in this path.
795  * @path:	The list to add devices to.
796  *
797  * The tree of Coresight device is traversed until an activated sink is
798  * found.  From there the sink is added to the list along with all the
799  * devices that led to that point - the end result is a list from source
800  * to sink. In that list the source is the first device and the sink the
801  * last one.
802  */
803 static int _coresight_build_path(struct coresight_device *csdev,
804 				 struct coresight_device *sink,
805 				 struct list_head *path)
806 {
807 	int i, ret;
808 	bool found = false;
809 	struct coresight_node *node;
810 
811 	/* An activated sink has been found.  Enqueue the element */
812 	if (csdev == sink)
813 		goto out;
814 
815 	if (coresight_is_percpu_source(csdev) && coresight_is_percpu_sink(sink) &&
816 	    sink == per_cpu(csdev_sink, source_ops(csdev)->cpu_id(csdev))) {
817 		if (_coresight_build_path(sink, sink, path) == 0) {
818 			found = true;
819 			goto out;
820 		}
821 	}
822 
823 	/* Not a sink - recursively explore each port found on this element */
824 	for (i = 0; i < csdev->pdata->nr_outconns; i++) {
825 		struct coresight_device *child_dev;
826 
827 		child_dev = csdev->pdata->out_conns[i]->dest_dev;
828 		if (child_dev &&
829 		    _coresight_build_path(child_dev, sink, path) == 0) {
830 			found = true;
831 			break;
832 		}
833 	}
834 
835 	if (!found)
836 		return -ENODEV;
837 
838 out:
839 	/*
840 	 * A path from this element to a sink has been found.  The elements
841 	 * leading to the sink are already enqueued, all that is left to do
842 	 * is tell the PM runtime core we need this element and add a node
843 	 * for it.
844 	 */
845 	ret = coresight_grab_device(csdev);
846 	if (ret)
847 		return ret;
848 
849 	node = kzalloc(sizeof(struct coresight_node), GFP_KERNEL);
850 	if (!node)
851 		return -ENOMEM;
852 
853 	node->csdev = csdev;
854 	list_add(&node->link, path);
855 
856 	return 0;
857 }
858 
859 struct list_head *coresight_build_path(struct coresight_device *source,
860 				       struct coresight_device *sink)
861 {
862 	struct list_head *path;
863 	int rc;
864 
865 	if (!sink)
866 		return ERR_PTR(-EINVAL);
867 
868 	path = kzalloc(sizeof(struct list_head), GFP_KERNEL);
869 	if (!path)
870 		return ERR_PTR(-ENOMEM);
871 
872 	INIT_LIST_HEAD(path);
873 
874 	rc = _coresight_build_path(source, sink, path);
875 	if (rc) {
876 		kfree(path);
877 		return ERR_PTR(rc);
878 	}
879 
880 	return path;
881 }
882 
883 /**
884  * coresight_release_path - release a previously built path.
885  * @path:	the path to release.
886  *
887  * Go through all the elements of a path and 1) removed it from the list and
888  * 2) free the memory allocated for each node.
889  */
890 void coresight_release_path(struct list_head *path)
891 {
892 	struct coresight_device *csdev;
893 	struct coresight_node *nd, *next;
894 
895 	list_for_each_entry_safe(nd, next, path, link) {
896 		csdev = nd->csdev;
897 
898 		coresight_drop_device(csdev);
899 		list_del(&nd->link);
900 		kfree(nd);
901 	}
902 
903 	kfree(path);
904 }
905 
906 /* return true if the device is a suitable type for a default sink */
907 static inline bool coresight_is_def_sink_type(struct coresight_device *csdev)
908 {
909 	/* sink & correct subtype */
910 	if (((csdev->type == CORESIGHT_DEV_TYPE_SINK) ||
911 	     (csdev->type == CORESIGHT_DEV_TYPE_LINKSINK)) &&
912 	    (csdev->subtype.sink_subtype >= CORESIGHT_DEV_SUBTYPE_SINK_BUFFER))
913 		return true;
914 	return false;
915 }
916 
917 /**
918  * coresight_select_best_sink - return the best sink for use as default from
919  * the two provided.
920  *
921  * @sink:	current best sink.
922  * @depth:      search depth where current sink was found.
923  * @new_sink:	new sink for comparison with current sink.
924  * @new_depth:  search depth where new sink was found.
925  *
926  * Sinks prioritised according to coresight_dev_subtype_sink, with only
927  * subtypes CORESIGHT_DEV_SUBTYPE_SINK_BUFFER or higher being used.
928  *
929  * Where two sinks of equal priority are found, the sink closest to the
930  * source is used (smallest search depth).
931  *
932  * return @new_sink & update @depth if better than @sink, else return @sink.
933  */
934 static struct coresight_device *
935 coresight_select_best_sink(struct coresight_device *sink, int *depth,
936 			   struct coresight_device *new_sink, int new_depth)
937 {
938 	bool update = false;
939 
940 	if (!sink) {
941 		/* first found at this level */
942 		update = true;
943 	} else if (new_sink->subtype.sink_subtype >
944 		   sink->subtype.sink_subtype) {
945 		/* found better sink */
946 		update = true;
947 	} else if ((new_sink->subtype.sink_subtype ==
948 		    sink->subtype.sink_subtype) &&
949 		   (*depth > new_depth)) {
950 		/* found same but closer sink */
951 		update = true;
952 	}
953 
954 	if (update)
955 		*depth = new_depth;
956 	return update ? new_sink : sink;
957 }
958 
959 /**
960  * coresight_find_sink - recursive function to walk trace connections from
961  * source to find a suitable default sink.
962  *
963  * @csdev: source / current device to check.
964  * @depth: [in] search depth of calling dev, [out] depth of found sink.
965  *
966  * This will walk the connection path from a source (ETM) till a suitable
967  * sink is encountered and return that sink to the original caller.
968  *
969  * If current device is a plain sink return that & depth, otherwise recursively
970  * call child connections looking for a sink. Select best possible using
971  * coresight_select_best_sink.
972  *
973  * return best sink found, or NULL if not found at this node or child nodes.
974  */
975 static struct coresight_device *
976 coresight_find_sink(struct coresight_device *csdev, int *depth)
977 {
978 	int i, curr_depth = *depth + 1, found_depth = 0;
979 	struct coresight_device *found_sink = NULL;
980 
981 	if (coresight_is_def_sink_type(csdev)) {
982 		found_depth = curr_depth;
983 		found_sink = csdev;
984 		if (csdev->type == CORESIGHT_DEV_TYPE_SINK)
985 			goto return_def_sink;
986 		/* look past LINKSINK for something better */
987 	}
988 
989 	/*
990 	 * Not a sink we want - or possible child sink may be better.
991 	 * recursively explore each port found on this element.
992 	 */
993 	for (i = 0; i < csdev->pdata->nr_outconns; i++) {
994 		struct coresight_device *child_dev, *sink = NULL;
995 		int child_depth = curr_depth;
996 
997 		child_dev = csdev->pdata->out_conns[i]->dest_dev;
998 		if (child_dev)
999 			sink = coresight_find_sink(child_dev, &child_depth);
1000 
1001 		if (sink)
1002 			found_sink = coresight_select_best_sink(found_sink,
1003 								&found_depth,
1004 								sink,
1005 								child_depth);
1006 	}
1007 
1008 return_def_sink:
1009 	/* return found sink and depth */
1010 	if (found_sink)
1011 		*depth = found_depth;
1012 	return found_sink;
1013 }
1014 
1015 /**
1016  * coresight_find_default_sink: Find a sink suitable for use as a
1017  * default sink.
1018  *
1019  * @csdev: starting source to find a connected sink.
1020  *
1021  * Walks connections graph looking for a suitable sink to enable for the
1022  * supplied source. Uses CoreSight device subtypes and distance from source
1023  * to select the best sink.
1024  *
1025  * If a sink is found, then the default sink for this device is set and
1026  * will be automatically used in future.
1027  *
1028  * Used in cases where the CoreSight user (perf / sysfs) has not selected a
1029  * sink.
1030  */
1031 struct coresight_device *
1032 coresight_find_default_sink(struct coresight_device *csdev)
1033 {
1034 	int depth = 0;
1035 
1036 	/* look for a default sink if we have not found for this device */
1037 	if (!csdev->def_sink) {
1038 		if (coresight_is_percpu_source(csdev))
1039 			csdev->def_sink = per_cpu(csdev_sink, source_ops(csdev)->cpu_id(csdev));
1040 		if (!csdev->def_sink)
1041 			csdev->def_sink = coresight_find_sink(csdev, &depth);
1042 	}
1043 	return csdev->def_sink;
1044 }
1045 
1046 static int coresight_remove_sink_ref(struct device *dev, void *data)
1047 {
1048 	struct coresight_device *sink = data;
1049 	struct coresight_device *source = to_coresight_device(dev);
1050 
1051 	if (source->def_sink == sink)
1052 		source->def_sink = NULL;
1053 	return 0;
1054 }
1055 
1056 /**
1057  * coresight_clear_default_sink: Remove all default sink references to the
1058  * supplied sink.
1059  *
1060  * If supplied device is a sink, then check all the bus devices and clear
1061  * out all the references to this sink from the coresight_device def_sink
1062  * parameter.
1063  *
1064  * @csdev: coresight sink - remove references to this from all sources.
1065  */
1066 static void coresight_clear_default_sink(struct coresight_device *csdev)
1067 {
1068 	if ((csdev->type == CORESIGHT_DEV_TYPE_SINK) ||
1069 	    (csdev->type == CORESIGHT_DEV_TYPE_LINKSINK)) {
1070 		bus_for_each_dev(&coresight_bustype, NULL, csdev,
1071 				 coresight_remove_sink_ref);
1072 	}
1073 }
1074 
1075 /** coresight_validate_source - make sure a source has the right credentials
1076  *  @csdev:	the device structure for a source.
1077  *  @function:	the function this was called from.
1078  *
1079  * Assumes the coresight_mutex is held.
1080  */
1081 static int coresight_validate_source(struct coresight_device *csdev,
1082 				     const char *function)
1083 {
1084 	u32 type, subtype;
1085 
1086 	type = csdev->type;
1087 	subtype = csdev->subtype.source_subtype;
1088 
1089 	if (type != CORESIGHT_DEV_TYPE_SOURCE) {
1090 		dev_err(&csdev->dev, "wrong device type in %s\n", function);
1091 		return -EINVAL;
1092 	}
1093 
1094 	if (subtype != CORESIGHT_DEV_SUBTYPE_SOURCE_PROC &&
1095 	    subtype != CORESIGHT_DEV_SUBTYPE_SOURCE_SOFTWARE &&
1096 	    subtype != CORESIGHT_DEV_SUBTYPE_SOURCE_OTHERS) {
1097 		dev_err(&csdev->dev, "wrong device subtype in %s\n", function);
1098 		return -EINVAL;
1099 	}
1100 
1101 	return 0;
1102 }
1103 
1104 int coresight_enable(struct coresight_device *csdev)
1105 {
1106 	int cpu, ret = 0;
1107 	struct coresight_device *sink;
1108 	struct list_head *path;
1109 	enum coresight_dev_subtype_source subtype;
1110 	u32 hash;
1111 
1112 	subtype = csdev->subtype.source_subtype;
1113 
1114 	mutex_lock(&coresight_mutex);
1115 
1116 	ret = coresight_validate_source(csdev, __func__);
1117 	if (ret)
1118 		goto out;
1119 
1120 	if (csdev->enable) {
1121 		/*
1122 		 * There could be multiple applications driving the software
1123 		 * source. So keep the refcount for each such user when the
1124 		 * source is already enabled.
1125 		 */
1126 		if (subtype == CORESIGHT_DEV_SUBTYPE_SOURCE_SOFTWARE)
1127 			atomic_inc(&csdev->refcnt);
1128 		goto out;
1129 	}
1130 
1131 	sink = coresight_get_enabled_sink(csdev);
1132 	if (!sink) {
1133 		ret = -EINVAL;
1134 		goto out;
1135 	}
1136 
1137 	path = coresight_build_path(csdev, sink);
1138 	if (IS_ERR(path)) {
1139 		pr_err("building path(s) failed\n");
1140 		ret = PTR_ERR(path);
1141 		goto out;
1142 	}
1143 
1144 	ret = coresight_enable_path(path, CS_MODE_SYSFS, NULL);
1145 	if (ret)
1146 		goto err_path;
1147 
1148 	ret = coresight_enable_source(csdev, CS_MODE_SYSFS, NULL);
1149 	if (ret)
1150 		goto err_source;
1151 
1152 	switch (subtype) {
1153 	case CORESIGHT_DEV_SUBTYPE_SOURCE_PROC:
1154 		/*
1155 		 * When working from sysFS it is important to keep track
1156 		 * of the paths that were created so that they can be
1157 		 * undone in 'coresight_disable()'.  Since there can only
1158 		 * be a single session per tracer (when working from sysFS)
1159 		 * a per-cpu variable will do just fine.
1160 		 */
1161 		cpu = source_ops(csdev)->cpu_id(csdev);
1162 		per_cpu(tracer_path, cpu) = path;
1163 		break;
1164 	case CORESIGHT_DEV_SUBTYPE_SOURCE_SOFTWARE:
1165 	case CORESIGHT_DEV_SUBTYPE_SOURCE_OTHERS:
1166 		/*
1167 		 * Use the hash of source's device name as ID
1168 		 * and map the ID to the pointer of the path.
1169 		 */
1170 		hash = hashlen_hash(hashlen_string(NULL, dev_name(&csdev->dev)));
1171 		ret = idr_alloc_u32(&path_idr, path, &hash, hash, GFP_KERNEL);
1172 		if (ret)
1173 			goto err_source;
1174 		break;
1175 	default:
1176 		/* We can't be here */
1177 		break;
1178 	}
1179 
1180 out:
1181 	mutex_unlock(&coresight_mutex);
1182 	return ret;
1183 
1184 err_source:
1185 	coresight_disable_path(path);
1186 
1187 err_path:
1188 	coresight_release_path(path);
1189 	goto out;
1190 }
1191 EXPORT_SYMBOL_GPL(coresight_enable);
1192 
1193 void coresight_disable(struct coresight_device *csdev)
1194 {
1195 	int cpu, ret;
1196 	struct list_head *path = NULL;
1197 	u32 hash;
1198 
1199 	mutex_lock(&coresight_mutex);
1200 
1201 	ret = coresight_validate_source(csdev, __func__);
1202 	if (ret)
1203 		goto out;
1204 
1205 	if (!csdev->enable || !coresight_disable_source(csdev, NULL))
1206 		goto out;
1207 
1208 	switch (csdev->subtype.source_subtype) {
1209 	case CORESIGHT_DEV_SUBTYPE_SOURCE_PROC:
1210 		cpu = source_ops(csdev)->cpu_id(csdev);
1211 		path = per_cpu(tracer_path, cpu);
1212 		per_cpu(tracer_path, cpu) = NULL;
1213 		break;
1214 	case CORESIGHT_DEV_SUBTYPE_SOURCE_SOFTWARE:
1215 	case CORESIGHT_DEV_SUBTYPE_SOURCE_OTHERS:
1216 		hash = hashlen_hash(hashlen_string(NULL, dev_name(&csdev->dev)));
1217 		/* Find the path by the hash. */
1218 		path = idr_find(&path_idr, hash);
1219 		if (path == NULL) {
1220 			pr_err("Path is not found for %s\n", dev_name(&csdev->dev));
1221 			goto out;
1222 		}
1223 		idr_remove(&path_idr, hash);
1224 		break;
1225 	default:
1226 		/* We can't be here */
1227 		break;
1228 	}
1229 
1230 	coresight_disable_path(path);
1231 	coresight_release_path(path);
1232 
1233 out:
1234 	mutex_unlock(&coresight_mutex);
1235 }
1236 EXPORT_SYMBOL_GPL(coresight_disable);
1237 
1238 static ssize_t enable_sink_show(struct device *dev,
1239 				struct device_attribute *attr, char *buf)
1240 {
1241 	struct coresight_device *csdev = to_coresight_device(dev);
1242 
1243 	return scnprintf(buf, PAGE_SIZE, "%u\n", csdev->activated);
1244 }
1245 
1246 static ssize_t enable_sink_store(struct device *dev,
1247 				 struct device_attribute *attr,
1248 				 const char *buf, size_t size)
1249 {
1250 	int ret;
1251 	unsigned long val;
1252 	struct coresight_device *csdev = to_coresight_device(dev);
1253 
1254 	ret = kstrtoul(buf, 10, &val);
1255 	if (ret)
1256 		return ret;
1257 
1258 	if (val)
1259 		csdev->activated = true;
1260 	else
1261 		csdev->activated = false;
1262 
1263 	return size;
1264 
1265 }
1266 static DEVICE_ATTR_RW(enable_sink);
1267 
1268 static ssize_t enable_source_show(struct device *dev,
1269 				  struct device_attribute *attr, char *buf)
1270 {
1271 	struct coresight_device *csdev = to_coresight_device(dev);
1272 
1273 	return scnprintf(buf, PAGE_SIZE, "%u\n", csdev->enable);
1274 }
1275 
1276 static ssize_t enable_source_store(struct device *dev,
1277 				   struct device_attribute *attr,
1278 				   const char *buf, size_t size)
1279 {
1280 	int ret = 0;
1281 	unsigned long val;
1282 	struct coresight_device *csdev = to_coresight_device(dev);
1283 
1284 	ret = kstrtoul(buf, 10, &val);
1285 	if (ret)
1286 		return ret;
1287 
1288 	if (val) {
1289 		ret = coresight_enable(csdev);
1290 		if (ret)
1291 			return ret;
1292 	} else {
1293 		coresight_disable(csdev);
1294 	}
1295 
1296 	return size;
1297 }
1298 static DEVICE_ATTR_RW(enable_source);
1299 
1300 static struct attribute *coresight_sink_attrs[] = {
1301 	&dev_attr_enable_sink.attr,
1302 	NULL,
1303 };
1304 ATTRIBUTE_GROUPS(coresight_sink);
1305 
1306 static struct attribute *coresight_source_attrs[] = {
1307 	&dev_attr_enable_source.attr,
1308 	NULL,
1309 };
1310 ATTRIBUTE_GROUPS(coresight_source);
1311 
1312 static struct device_type coresight_dev_type[] = {
1313 	{
1314 		.name = "sink",
1315 		.groups = coresight_sink_groups,
1316 	},
1317 	{
1318 		.name = "link",
1319 	},
1320 	{
1321 		.name = "linksink",
1322 		.groups = coresight_sink_groups,
1323 	},
1324 	{
1325 		.name = "source",
1326 		.groups = coresight_source_groups,
1327 	},
1328 	{
1329 		.name = "helper",
1330 	}
1331 };
1332 /* Ensure the enum matches the names and groups */
1333 static_assert(ARRAY_SIZE(coresight_dev_type) == CORESIGHT_DEV_TYPE_MAX);
1334 
1335 static void coresight_device_release(struct device *dev)
1336 {
1337 	struct coresight_device *csdev = to_coresight_device(dev);
1338 
1339 	fwnode_handle_put(csdev->dev.fwnode);
1340 	kfree(csdev);
1341 }
1342 
1343 static int coresight_orphan_match(struct device *dev, void *data)
1344 {
1345 	int i, ret = 0;
1346 	bool still_orphan = false;
1347 	struct coresight_device *dst_csdev = data;
1348 	struct coresight_device *src_csdev = to_coresight_device(dev);
1349 	struct coresight_connection *conn;
1350 	bool fixup_self = (src_csdev == dst_csdev);
1351 
1352 	/* Move on to another component if no connection is orphan */
1353 	if (!src_csdev->orphan)
1354 		return 0;
1355 	/*
1356 	 * Circle through all the connections of that component.  If we find
1357 	 * an orphan connection whose name matches @dst_csdev, link it.
1358 	 */
1359 	for (i = 0; i < src_csdev->pdata->nr_outconns; i++) {
1360 		conn = src_csdev->pdata->out_conns[i];
1361 
1362 		/* Skip the port if it's already connected. */
1363 		if (conn->dest_dev)
1364 			continue;
1365 
1366 		/*
1367 		 * If we are at the "new" device, which triggered this search,
1368 		 * we must find the remote device from the fwnode in the
1369 		 * connection.
1370 		 */
1371 		if (fixup_self)
1372 			dst_csdev = coresight_find_csdev_by_fwnode(
1373 				conn->dest_fwnode);
1374 
1375 		/* Does it match this newly added device? */
1376 		if (dst_csdev && conn->dest_fwnode == dst_csdev->dev.fwnode) {
1377 			ret = coresight_make_links(src_csdev, conn, dst_csdev);
1378 			if (ret)
1379 				return ret;
1380 
1381 			/*
1382 			 * Install the device connection. This also indicates that
1383 			 * the links are operational on both ends.
1384 			 */
1385 			conn->dest_dev = dst_csdev;
1386 			conn->src_dev = src_csdev;
1387 
1388 			ret = coresight_add_in_conn(conn);
1389 			if (ret)
1390 				return ret;
1391 		} else {
1392 			/* This component still has an orphan */
1393 			still_orphan = true;
1394 		}
1395 	}
1396 
1397 	src_csdev->orphan = still_orphan;
1398 
1399 	/*
1400 	 * Returning '0' in case we didn't encounter any error,
1401 	 * ensures that all known component on the bus will be checked.
1402 	 */
1403 	return 0;
1404 }
1405 
1406 static int coresight_fixup_orphan_conns(struct coresight_device *csdev)
1407 {
1408 	return bus_for_each_dev(&coresight_bustype, NULL,
1409 			 csdev, coresight_orphan_match);
1410 }
1411 
1412 /* coresight_remove_conns - Remove other device's references to this device */
1413 static void coresight_remove_conns(struct coresight_device *csdev)
1414 {
1415 	int i, j;
1416 	struct coresight_connection *conn;
1417 
1418 	/*
1419 	 * Remove the input connection references from the destination device
1420 	 * for each output connection.
1421 	 */
1422 	for (i = 0; i < csdev->pdata->nr_outconns; i++) {
1423 		conn = csdev->pdata->out_conns[i];
1424 		if (!conn->dest_dev)
1425 			continue;
1426 
1427 		for (j = 0; j < conn->dest_dev->pdata->nr_inconns; ++j)
1428 			if (conn->dest_dev->pdata->in_conns[j] == conn) {
1429 				conn->dest_dev->pdata->in_conns[j] = NULL;
1430 				break;
1431 			}
1432 	}
1433 
1434 	/*
1435 	 * For all input connections, remove references to this device.
1436 	 * Connection objects are shared so modifying this device's input
1437 	 * connections affects the other device's output connection.
1438 	 */
1439 	for (i = 0; i < csdev->pdata->nr_inconns; ++i) {
1440 		conn = csdev->pdata->in_conns[i];
1441 		/* Input conns array is sparse */
1442 		if (!conn)
1443 			continue;
1444 
1445 		conn->src_dev->orphan = true;
1446 		coresight_remove_links(conn->src_dev, conn);
1447 		conn->dest_dev = NULL;
1448 	}
1449 }
1450 
1451 /**
1452  * coresight_timeout - loop until a bit has changed to a specific register
1453  *			state.
1454  * @csa: coresight device access for the device
1455  * @offset: Offset of the register from the base of the device.
1456  * @position: the position of the bit of interest.
1457  * @value: the value the bit should have.
1458  *
1459  * Return: 0 as soon as the bit has taken the desired state or -EAGAIN if
1460  * TIMEOUT_US has elapsed, which ever happens first.
1461  */
1462 int coresight_timeout(struct csdev_access *csa, u32 offset,
1463 		      int position, int value)
1464 {
1465 	int i;
1466 	u32 val;
1467 
1468 	for (i = TIMEOUT_US; i > 0; i--) {
1469 		val = csdev_access_read32(csa, offset);
1470 		/* waiting on the bit to go from 0 to 1 */
1471 		if (value) {
1472 			if (val & BIT(position))
1473 				return 0;
1474 		/* waiting on the bit to go from 1 to 0 */
1475 		} else {
1476 			if (!(val & BIT(position)))
1477 				return 0;
1478 		}
1479 
1480 		/*
1481 		 * Delay is arbitrary - the specification doesn't say how long
1482 		 * we are expected to wait.  Extra check required to make sure
1483 		 * we don't wait needlessly on the last iteration.
1484 		 */
1485 		if (i - 1)
1486 			udelay(1);
1487 	}
1488 
1489 	return -EAGAIN;
1490 }
1491 EXPORT_SYMBOL_GPL(coresight_timeout);
1492 
1493 u32 coresight_relaxed_read32(struct coresight_device *csdev, u32 offset)
1494 {
1495 	return csdev_access_relaxed_read32(&csdev->access, offset);
1496 }
1497 
1498 u32 coresight_read32(struct coresight_device *csdev, u32 offset)
1499 {
1500 	return csdev_access_read32(&csdev->access, offset);
1501 }
1502 
1503 void coresight_relaxed_write32(struct coresight_device *csdev,
1504 			       u32 val, u32 offset)
1505 {
1506 	csdev_access_relaxed_write32(&csdev->access, val, offset);
1507 }
1508 
1509 void coresight_write32(struct coresight_device *csdev, u32 val, u32 offset)
1510 {
1511 	csdev_access_write32(&csdev->access, val, offset);
1512 }
1513 
1514 u64 coresight_relaxed_read64(struct coresight_device *csdev, u32 offset)
1515 {
1516 	return csdev_access_relaxed_read64(&csdev->access, offset);
1517 }
1518 
1519 u64 coresight_read64(struct coresight_device *csdev, u32 offset)
1520 {
1521 	return csdev_access_read64(&csdev->access, offset);
1522 }
1523 
1524 void coresight_relaxed_write64(struct coresight_device *csdev,
1525 			       u64 val, u32 offset)
1526 {
1527 	csdev_access_relaxed_write64(&csdev->access, val, offset);
1528 }
1529 
1530 void coresight_write64(struct coresight_device *csdev, u64 val, u32 offset)
1531 {
1532 	csdev_access_write64(&csdev->access, val, offset);
1533 }
1534 
1535 /*
1536  * coresight_release_platform_data: Release references to the devices connected
1537  * to the output port of this device.
1538  */
1539 void coresight_release_platform_data(struct coresight_device *csdev,
1540 				     struct device *dev,
1541 				     struct coresight_platform_data *pdata)
1542 {
1543 	int i;
1544 	struct coresight_connection **conns = pdata->out_conns;
1545 
1546 	for (i = 0; i < pdata->nr_outconns; i++) {
1547 		/* If we have made the links, remove them now */
1548 		if (csdev && conns[i]->dest_dev)
1549 			coresight_remove_links(csdev, conns[i]);
1550 		/*
1551 		 * Drop the refcount and clear the handle as this device
1552 		 * is going away
1553 		 */
1554 		fwnode_handle_put(conns[i]->dest_fwnode);
1555 		conns[i]->dest_fwnode = NULL;
1556 		devm_kfree(dev, conns[i]);
1557 	}
1558 	devm_kfree(dev, pdata->out_conns);
1559 	devm_kfree(dev, pdata->in_conns);
1560 	devm_kfree(dev, pdata);
1561 	if (csdev)
1562 		coresight_remove_conns_sysfs_group(csdev);
1563 }
1564 
1565 struct coresight_device *coresight_register(struct coresight_desc *desc)
1566 {
1567 	int ret;
1568 	struct coresight_device *csdev;
1569 	bool registered = false;
1570 
1571 	csdev = kzalloc(sizeof(*csdev), GFP_KERNEL);
1572 	if (!csdev) {
1573 		ret = -ENOMEM;
1574 		goto err_out;
1575 	}
1576 
1577 	csdev->pdata = desc->pdata;
1578 
1579 	csdev->type = desc->type;
1580 	csdev->subtype = desc->subtype;
1581 	csdev->ops = desc->ops;
1582 	csdev->access = desc->access;
1583 	csdev->orphan = true;
1584 
1585 	csdev->dev.type = &coresight_dev_type[desc->type];
1586 	csdev->dev.groups = desc->groups;
1587 	csdev->dev.parent = desc->dev;
1588 	csdev->dev.release = coresight_device_release;
1589 	csdev->dev.bus = &coresight_bustype;
1590 	/*
1591 	 * Hold the reference to our parent device. This will be
1592 	 * dropped only in coresight_device_release().
1593 	 */
1594 	csdev->dev.fwnode = fwnode_handle_get(dev_fwnode(desc->dev));
1595 	dev_set_name(&csdev->dev, "%s", desc->name);
1596 
1597 	/*
1598 	 * Make sure the device registration and the connection fixup
1599 	 * are synchronised, so that we don't see uninitialised devices
1600 	 * on the coresight bus while trying to resolve the connections.
1601 	 */
1602 	mutex_lock(&coresight_mutex);
1603 
1604 	ret = device_register(&csdev->dev);
1605 	if (ret) {
1606 		put_device(&csdev->dev);
1607 		/*
1608 		 * All resources are free'd explicitly via
1609 		 * coresight_device_release(), triggered from put_device().
1610 		 */
1611 		goto out_unlock;
1612 	}
1613 
1614 	if (csdev->type == CORESIGHT_DEV_TYPE_SINK ||
1615 	    csdev->type == CORESIGHT_DEV_TYPE_LINKSINK) {
1616 		ret = etm_perf_add_symlink_sink(csdev);
1617 
1618 		if (ret) {
1619 			device_unregister(&csdev->dev);
1620 			/*
1621 			 * As with the above, all resources are free'd
1622 			 * explicitly via coresight_device_release() triggered
1623 			 * from put_device(), which is in turn called from
1624 			 * function device_unregister().
1625 			 */
1626 			goto out_unlock;
1627 		}
1628 	}
1629 	/* Device is now registered */
1630 	registered = true;
1631 
1632 	ret = coresight_create_conns_sysfs_group(csdev);
1633 	if (!ret)
1634 		ret = coresight_fixup_orphan_conns(csdev);
1635 
1636 out_unlock:
1637 	mutex_unlock(&coresight_mutex);
1638 	/* Success */
1639 	if (!ret) {
1640 		if (cti_assoc_ops && cti_assoc_ops->add)
1641 			cti_assoc_ops->add(csdev);
1642 		return csdev;
1643 	}
1644 
1645 	/* Unregister the device if needed */
1646 	if (registered) {
1647 		coresight_unregister(csdev);
1648 		return ERR_PTR(ret);
1649 	}
1650 
1651 err_out:
1652 	/* Cleanup the connection information */
1653 	coresight_release_platform_data(NULL, desc->dev, desc->pdata);
1654 	return ERR_PTR(ret);
1655 }
1656 EXPORT_SYMBOL_GPL(coresight_register);
1657 
1658 void coresight_unregister(struct coresight_device *csdev)
1659 {
1660 	etm_perf_del_symlink_sink(csdev);
1661 	/* Remove references of that device in the topology */
1662 	if (cti_assoc_ops && cti_assoc_ops->remove)
1663 		cti_assoc_ops->remove(csdev);
1664 	coresight_remove_conns(csdev);
1665 	coresight_clear_default_sink(csdev);
1666 	coresight_release_platform_data(csdev, csdev->dev.parent, csdev->pdata);
1667 	device_unregister(&csdev->dev);
1668 }
1669 EXPORT_SYMBOL_GPL(coresight_unregister);
1670 
1671 
1672 /*
1673  * coresight_search_device_idx - Search the fwnode handle of a device
1674  * in the given dev_idx list. Must be called with the coresight_mutex held.
1675  *
1676  * Returns the index of the entry, when found. Otherwise, -ENOENT.
1677  */
1678 static inline int coresight_search_device_idx(struct coresight_dev_list *dict,
1679 					      struct fwnode_handle *fwnode)
1680 {
1681 	int i;
1682 
1683 	for (i = 0; i < dict->nr_idx; i++)
1684 		if (dict->fwnode_list[i] == fwnode)
1685 			return i;
1686 	return -ENOENT;
1687 }
1688 
1689 static bool coresight_compare_type(enum coresight_dev_type type_a,
1690 				   union coresight_dev_subtype subtype_a,
1691 				   enum coresight_dev_type type_b,
1692 				   union coresight_dev_subtype subtype_b)
1693 {
1694 	if (type_a != type_b)
1695 		return false;
1696 
1697 	switch (type_a) {
1698 	case CORESIGHT_DEV_TYPE_SINK:
1699 		return subtype_a.sink_subtype == subtype_b.sink_subtype;
1700 	case CORESIGHT_DEV_TYPE_LINK:
1701 		return subtype_a.link_subtype == subtype_b.link_subtype;
1702 	case CORESIGHT_DEV_TYPE_LINKSINK:
1703 		return subtype_a.link_subtype == subtype_b.link_subtype &&
1704 		       subtype_a.sink_subtype == subtype_b.sink_subtype;
1705 	case CORESIGHT_DEV_TYPE_SOURCE:
1706 		return subtype_a.source_subtype == subtype_b.source_subtype;
1707 	case CORESIGHT_DEV_TYPE_HELPER:
1708 		return subtype_a.helper_subtype == subtype_b.helper_subtype;
1709 	default:
1710 		return false;
1711 	}
1712 }
1713 
1714 struct coresight_device *
1715 coresight_find_input_type(struct coresight_platform_data *pdata,
1716 			  enum coresight_dev_type type,
1717 			  union coresight_dev_subtype subtype)
1718 {
1719 	int i;
1720 	struct coresight_connection *conn;
1721 
1722 	for (i = 0; i < pdata->nr_inconns; ++i) {
1723 		conn = pdata->in_conns[i];
1724 		if (conn &&
1725 		    coresight_compare_type(type, subtype, conn->src_dev->type,
1726 					   conn->src_dev->subtype))
1727 			return conn->src_dev;
1728 	}
1729 	return NULL;
1730 }
1731 EXPORT_SYMBOL_GPL(coresight_find_input_type);
1732 
1733 struct coresight_device *
1734 coresight_find_output_type(struct coresight_platform_data *pdata,
1735 			   enum coresight_dev_type type,
1736 			   union coresight_dev_subtype subtype)
1737 {
1738 	int i;
1739 	struct coresight_connection *conn;
1740 
1741 	for (i = 0; i < pdata->nr_outconns; ++i) {
1742 		conn = pdata->out_conns[i];
1743 		if (conn->dest_dev &&
1744 		    coresight_compare_type(type, subtype, conn->dest_dev->type,
1745 					   conn->dest_dev->subtype))
1746 			return conn->dest_dev;
1747 	}
1748 	return NULL;
1749 }
1750 EXPORT_SYMBOL_GPL(coresight_find_output_type);
1751 
1752 bool coresight_loses_context_with_cpu(struct device *dev)
1753 {
1754 	return fwnode_property_present(dev_fwnode(dev),
1755 				       "arm,coresight-loses-context-with-cpu");
1756 }
1757 EXPORT_SYMBOL_GPL(coresight_loses_context_with_cpu);
1758 
1759 /*
1760  * coresight_alloc_device_name - Get an index for a given device in the
1761  * device index list specific to a driver. An index is allocated for a
1762  * device and is tracked with the fwnode_handle to prevent allocating
1763  * duplicate indices for the same device (e.g, if we defer probing of
1764  * a device due to dependencies), in case the index is requested again.
1765  */
1766 char *coresight_alloc_device_name(struct coresight_dev_list *dict,
1767 				  struct device *dev)
1768 {
1769 	int idx;
1770 	char *name = NULL;
1771 	struct fwnode_handle **list;
1772 
1773 	mutex_lock(&coresight_mutex);
1774 
1775 	idx = coresight_search_device_idx(dict, dev_fwnode(dev));
1776 	if (idx < 0) {
1777 		/* Make space for the new entry */
1778 		idx = dict->nr_idx;
1779 		list = krealloc_array(dict->fwnode_list,
1780 				      idx + 1, sizeof(*dict->fwnode_list),
1781 				      GFP_KERNEL);
1782 		if (ZERO_OR_NULL_PTR(list)) {
1783 			idx = -ENOMEM;
1784 			goto done;
1785 		}
1786 
1787 		list[idx] = dev_fwnode(dev);
1788 		dict->fwnode_list = list;
1789 		dict->nr_idx = idx + 1;
1790 	}
1791 
1792 	name = devm_kasprintf(dev, GFP_KERNEL, "%s%d", dict->pfx, idx);
1793 done:
1794 	mutex_unlock(&coresight_mutex);
1795 	return name;
1796 }
1797 EXPORT_SYMBOL_GPL(coresight_alloc_device_name);
1798 
1799 struct bus_type coresight_bustype = {
1800 	.name	= "coresight",
1801 };
1802 
1803 static int __init coresight_init(void)
1804 {
1805 	int ret;
1806 
1807 	ret = bus_register(&coresight_bustype);
1808 	if (ret)
1809 		return ret;
1810 
1811 	ret = etm_perf_init();
1812 	if (ret)
1813 		goto exit_bus_unregister;
1814 
1815 	/* initialise the coresight syscfg API */
1816 	ret = cscfg_init();
1817 	if (!ret)
1818 		return 0;
1819 
1820 	etm_perf_exit();
1821 exit_bus_unregister:
1822 	bus_unregister(&coresight_bustype);
1823 	return ret;
1824 }
1825 
1826 static void __exit coresight_exit(void)
1827 {
1828 	cscfg_exit();
1829 	etm_perf_exit();
1830 	bus_unregister(&coresight_bustype);
1831 }
1832 
1833 module_init(coresight_init);
1834 module_exit(coresight_exit);
1835 
1836 MODULE_LICENSE("GPL v2");
1837 MODULE_AUTHOR("Pratik Patel <pratikp@codeaurora.org>");
1838 MODULE_AUTHOR("Mathieu Poirier <mathieu.poirier@linaro.org>");
1839 MODULE_DESCRIPTION("Arm CoreSight tracer driver");
1840