1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright(C) 2016 Linaro Limited. All rights reserved.
4  * Author: Mathieu Poirier <mathieu.poirier@linaro.org>
5  */
6 
7 #include <linux/atomic.h>
8 #include <linux/coresight.h>
9 #include <linux/dma-mapping.h>
10 #include <linux/iommu.h>
11 #include <linux/idr.h>
12 #include <linux/mutex.h>
13 #include <linux/refcount.h>
14 #include <linux/slab.h>
15 #include <linux/types.h>
16 #include <linux/vmalloc.h>
17 #include "coresight-catu.h"
18 #include "coresight-etm-perf.h"
19 #include "coresight-priv.h"
20 #include "coresight-tmc.h"
21 
22 struct etr_flat_buf {
23 	struct device	*dev;
24 	dma_addr_t	daddr;
25 	void		*vaddr;
26 	size_t		size;
27 };
28 
29 /*
30  * etr_perf_buffer - Perf buffer used for ETR
31  * @drvdata		- The ETR drvdaga this buffer has been allocated for.
32  * @etr_buf		- Actual buffer used by the ETR
33  * @pid			- The PID this etr_perf_buffer belongs to.
34  * @snaphost		- Perf session mode
35  * @head		- handle->head at the beginning of the session.
36  * @nr_pages		- Number of pages in the ring buffer.
37  * @pages		- Array of Pages in the ring buffer.
38  */
39 struct etr_perf_buffer {
40 	struct tmc_drvdata	*drvdata;
41 	struct etr_buf		*etr_buf;
42 	pid_t			pid;
43 	bool			snapshot;
44 	unsigned long		head;
45 	int			nr_pages;
46 	void			**pages;
47 };
48 
49 /* Convert the perf index to an offset within the ETR buffer */
50 #define PERF_IDX2OFF(idx, buf)	((idx) % ((buf)->nr_pages << PAGE_SHIFT))
51 
52 /* Lower limit for ETR hardware buffer */
53 #define TMC_ETR_PERF_MIN_BUF_SIZE	SZ_1M
54 
55 /*
56  * The TMC ETR SG has a page size of 4K. The SG table contains pointers
57  * to 4KB buffers. However, the OS may use a PAGE_SIZE different from
58  * 4K (i.e, 16KB or 64KB). This implies that a single OS page could
59  * contain more than one SG buffer and tables.
60  *
61  * A table entry has the following format:
62  *
63  * ---Bit31------------Bit4-------Bit1-----Bit0--
64  * |     Address[39:12]    | SBZ |  Entry Type  |
65  * ----------------------------------------------
66  *
67  * Address: Bits [39:12] of a physical page address. Bits [11:0] are
68  *	    always zero.
69  *
70  * Entry type:
71  *	b00 - Reserved.
72  *	b01 - Last entry in the tables, points to 4K page buffer.
73  *	b10 - Normal entry, points to 4K page buffer.
74  *	b11 - Link. The address points to the base of next table.
75  */
76 
77 typedef u32 sgte_t;
78 
79 #define ETR_SG_PAGE_SHIFT		12
80 #define ETR_SG_PAGE_SIZE		(1UL << ETR_SG_PAGE_SHIFT)
81 #define ETR_SG_PAGES_PER_SYSPAGE	(PAGE_SIZE / ETR_SG_PAGE_SIZE)
82 #define ETR_SG_PTRS_PER_PAGE		(ETR_SG_PAGE_SIZE / sizeof(sgte_t))
83 #define ETR_SG_PTRS_PER_SYSPAGE		(PAGE_SIZE / sizeof(sgte_t))
84 
85 #define ETR_SG_ET_MASK			0x3
86 #define ETR_SG_ET_LAST			0x1
87 #define ETR_SG_ET_NORMAL		0x2
88 #define ETR_SG_ET_LINK			0x3
89 
90 #define ETR_SG_ADDR_SHIFT		4
91 
92 #define ETR_SG_ENTRY(addr, type) \
93 	(sgte_t)((((addr) >> ETR_SG_PAGE_SHIFT) << ETR_SG_ADDR_SHIFT) | \
94 		 (type & ETR_SG_ET_MASK))
95 
96 #define ETR_SG_ADDR(entry) \
97 	(((dma_addr_t)(entry) >> ETR_SG_ADDR_SHIFT) << ETR_SG_PAGE_SHIFT)
98 #define ETR_SG_ET(entry)		((entry) & ETR_SG_ET_MASK)
99 
100 /*
101  * struct etr_sg_table : ETR SG Table
102  * @sg_table:		Generic SG Table holding the data/table pages.
103  * @hwaddr:		hwaddress used by the TMC, which is the base
104  *			address of the table.
105  */
106 struct etr_sg_table {
107 	struct tmc_sg_table	*sg_table;
108 	dma_addr_t		hwaddr;
109 };
110 
111 /*
112  * tmc_etr_sg_table_entries: Total number of table entries required to map
113  * @nr_pages system pages.
114  *
115  * We need to map @nr_pages * ETR_SG_PAGES_PER_SYSPAGE data pages.
116  * Each TMC page can map (ETR_SG_PTRS_PER_PAGE - 1) buffer pointers,
117  * with the last entry pointing to another page of table entries.
118  * If we spill over to a new page for mapping 1 entry, we could as
119  * well replace the link entry of the previous page with the last entry.
120  */
121 static inline unsigned long __attribute_const__
122 tmc_etr_sg_table_entries(int nr_pages)
123 {
124 	unsigned long nr_sgpages = nr_pages * ETR_SG_PAGES_PER_SYSPAGE;
125 	unsigned long nr_sglinks = nr_sgpages / (ETR_SG_PTRS_PER_PAGE - 1);
126 	/*
127 	 * If we spill over to a new page for 1 entry, we could as well
128 	 * make it the LAST entry in the previous page, skipping the Link
129 	 * address.
130 	 */
131 	if (nr_sglinks && (nr_sgpages % (ETR_SG_PTRS_PER_PAGE - 1) < 2))
132 		nr_sglinks--;
133 	return nr_sgpages + nr_sglinks;
134 }
135 
136 /*
137  * tmc_pages_get_offset:  Go through all the pages in the tmc_pages
138  * and map the device address @addr to an offset within the virtual
139  * contiguous buffer.
140  */
141 static long
142 tmc_pages_get_offset(struct tmc_pages *tmc_pages, dma_addr_t addr)
143 {
144 	int i;
145 	dma_addr_t page_start;
146 
147 	for (i = 0; i < tmc_pages->nr_pages; i++) {
148 		page_start = tmc_pages->daddrs[i];
149 		if (addr >= page_start && addr < (page_start + PAGE_SIZE))
150 			return i * PAGE_SIZE + (addr - page_start);
151 	}
152 
153 	return -EINVAL;
154 }
155 
156 /*
157  * tmc_pages_free : Unmap and free the pages used by tmc_pages.
158  * If the pages were not allocated in tmc_pages_alloc(), we would
159  * simply drop the refcount.
160  */
161 static void tmc_pages_free(struct tmc_pages *tmc_pages,
162 			   struct device *dev, enum dma_data_direction dir)
163 {
164 	int i;
165 	struct device *real_dev = dev->parent;
166 
167 	for (i = 0; i < tmc_pages->nr_pages; i++) {
168 		if (tmc_pages->daddrs && tmc_pages->daddrs[i])
169 			dma_unmap_page(real_dev, tmc_pages->daddrs[i],
170 					 PAGE_SIZE, dir);
171 		if (tmc_pages->pages && tmc_pages->pages[i])
172 			__free_page(tmc_pages->pages[i]);
173 	}
174 
175 	kfree(tmc_pages->pages);
176 	kfree(tmc_pages->daddrs);
177 	tmc_pages->pages = NULL;
178 	tmc_pages->daddrs = NULL;
179 	tmc_pages->nr_pages = 0;
180 }
181 
182 /*
183  * tmc_pages_alloc : Allocate and map pages for a given @tmc_pages.
184  * If @pages is not NULL, the list of page virtual addresses are
185  * used as the data pages. The pages are then dma_map'ed for @dev
186  * with dma_direction @dir.
187  *
188  * Returns 0 upon success, else the error number.
189  */
190 static int tmc_pages_alloc(struct tmc_pages *tmc_pages,
191 			   struct device *dev, int node,
192 			   enum dma_data_direction dir, void **pages)
193 {
194 	int i, nr_pages;
195 	dma_addr_t paddr;
196 	struct page *page;
197 	struct device *real_dev = dev->parent;
198 
199 	nr_pages = tmc_pages->nr_pages;
200 	tmc_pages->daddrs = kcalloc(nr_pages, sizeof(*tmc_pages->daddrs),
201 					 GFP_KERNEL);
202 	if (!tmc_pages->daddrs)
203 		return -ENOMEM;
204 	tmc_pages->pages = kcalloc(nr_pages, sizeof(*tmc_pages->pages),
205 					 GFP_KERNEL);
206 	if (!tmc_pages->pages) {
207 		kfree(tmc_pages->daddrs);
208 		tmc_pages->daddrs = NULL;
209 		return -ENOMEM;
210 	}
211 
212 	for (i = 0; i < nr_pages; i++) {
213 		if (pages && pages[i]) {
214 			page = virt_to_page(pages[i]);
215 			/* Hold a refcount on the page */
216 			get_page(page);
217 		} else {
218 			page = alloc_pages_node(node,
219 						GFP_KERNEL | __GFP_ZERO, 0);
220 		}
221 		paddr = dma_map_page(real_dev, page, 0, PAGE_SIZE, dir);
222 		if (dma_mapping_error(real_dev, paddr))
223 			goto err;
224 		tmc_pages->daddrs[i] = paddr;
225 		tmc_pages->pages[i] = page;
226 	}
227 	return 0;
228 err:
229 	tmc_pages_free(tmc_pages, dev, dir);
230 	return -ENOMEM;
231 }
232 
233 static inline long
234 tmc_sg_get_data_page_offset(struct tmc_sg_table *sg_table, dma_addr_t addr)
235 {
236 	return tmc_pages_get_offset(&sg_table->data_pages, addr);
237 }
238 
239 static inline void tmc_free_table_pages(struct tmc_sg_table *sg_table)
240 {
241 	if (sg_table->table_vaddr)
242 		vunmap(sg_table->table_vaddr);
243 	tmc_pages_free(&sg_table->table_pages, sg_table->dev, DMA_TO_DEVICE);
244 }
245 
246 static void tmc_free_data_pages(struct tmc_sg_table *sg_table)
247 {
248 	if (sg_table->data_vaddr)
249 		vunmap(sg_table->data_vaddr);
250 	tmc_pages_free(&sg_table->data_pages, sg_table->dev, DMA_FROM_DEVICE);
251 }
252 
253 void tmc_free_sg_table(struct tmc_sg_table *sg_table)
254 {
255 	tmc_free_table_pages(sg_table);
256 	tmc_free_data_pages(sg_table);
257 }
258 EXPORT_SYMBOL_GPL(tmc_free_sg_table);
259 
260 /*
261  * Alloc pages for the table. Since this will be used by the device,
262  * allocate the pages closer to the device (i.e, dev_to_node(dev)
263  * rather than the CPU node).
264  */
265 static int tmc_alloc_table_pages(struct tmc_sg_table *sg_table)
266 {
267 	int rc;
268 	struct tmc_pages *table_pages = &sg_table->table_pages;
269 
270 	rc = tmc_pages_alloc(table_pages, sg_table->dev,
271 			     dev_to_node(sg_table->dev),
272 			     DMA_TO_DEVICE, NULL);
273 	if (rc)
274 		return rc;
275 	sg_table->table_vaddr = vmap(table_pages->pages,
276 				     table_pages->nr_pages,
277 				     VM_MAP,
278 				     PAGE_KERNEL);
279 	if (!sg_table->table_vaddr)
280 		rc = -ENOMEM;
281 	else
282 		sg_table->table_daddr = table_pages->daddrs[0];
283 	return rc;
284 }
285 
286 static int tmc_alloc_data_pages(struct tmc_sg_table *sg_table, void **pages)
287 {
288 	int rc;
289 
290 	/* Allocate data pages on the node requested by the caller */
291 	rc = tmc_pages_alloc(&sg_table->data_pages,
292 			     sg_table->dev, sg_table->node,
293 			     DMA_FROM_DEVICE, pages);
294 	if (!rc) {
295 		sg_table->data_vaddr = vmap(sg_table->data_pages.pages,
296 					    sg_table->data_pages.nr_pages,
297 					    VM_MAP,
298 					    PAGE_KERNEL);
299 		if (!sg_table->data_vaddr)
300 			rc = -ENOMEM;
301 	}
302 	return rc;
303 }
304 
305 /*
306  * tmc_alloc_sg_table: Allocate and setup dma pages for the TMC SG table
307  * and data buffers. TMC writes to the data buffers and reads from the SG
308  * Table pages.
309  *
310  * @dev		- Coresight device to which page should be DMA mapped.
311  * @node	- Numa node for mem allocations
312  * @nr_tpages	- Number of pages for the table entries.
313  * @nr_dpages	- Number of pages for Data buffer.
314  * @pages	- Optional list of virtual address of pages.
315  */
316 struct tmc_sg_table *tmc_alloc_sg_table(struct device *dev,
317 					int node,
318 					int nr_tpages,
319 					int nr_dpages,
320 					void **pages)
321 {
322 	long rc;
323 	struct tmc_sg_table *sg_table;
324 
325 	sg_table = kzalloc(sizeof(*sg_table), GFP_KERNEL);
326 	if (!sg_table)
327 		return ERR_PTR(-ENOMEM);
328 	sg_table->data_pages.nr_pages = nr_dpages;
329 	sg_table->table_pages.nr_pages = nr_tpages;
330 	sg_table->node = node;
331 	sg_table->dev = dev;
332 
333 	rc  = tmc_alloc_data_pages(sg_table, pages);
334 	if (!rc)
335 		rc = tmc_alloc_table_pages(sg_table);
336 	if (rc) {
337 		tmc_free_sg_table(sg_table);
338 		kfree(sg_table);
339 		return ERR_PTR(rc);
340 	}
341 
342 	return sg_table;
343 }
344 EXPORT_SYMBOL_GPL(tmc_alloc_sg_table);
345 
346 /*
347  * tmc_sg_table_sync_data_range: Sync the data buffer written
348  * by the device from @offset upto a @size bytes.
349  */
350 void tmc_sg_table_sync_data_range(struct tmc_sg_table *table,
351 				  u64 offset, u64 size)
352 {
353 	int i, index, start;
354 	int npages = DIV_ROUND_UP(size, PAGE_SIZE);
355 	struct device *real_dev = table->dev->parent;
356 	struct tmc_pages *data = &table->data_pages;
357 
358 	start = offset >> PAGE_SHIFT;
359 	for (i = start; i < (start + npages); i++) {
360 		index = i % data->nr_pages;
361 		dma_sync_single_for_cpu(real_dev, data->daddrs[index],
362 					PAGE_SIZE, DMA_FROM_DEVICE);
363 	}
364 }
365 EXPORT_SYMBOL_GPL(tmc_sg_table_sync_data_range);
366 
367 /* tmc_sg_sync_table: Sync the page table */
368 void tmc_sg_table_sync_table(struct tmc_sg_table *sg_table)
369 {
370 	int i;
371 	struct device *real_dev = sg_table->dev->parent;
372 	struct tmc_pages *table_pages = &sg_table->table_pages;
373 
374 	for (i = 0; i < table_pages->nr_pages; i++)
375 		dma_sync_single_for_device(real_dev, table_pages->daddrs[i],
376 					   PAGE_SIZE, DMA_TO_DEVICE);
377 }
378 EXPORT_SYMBOL_GPL(tmc_sg_table_sync_table);
379 
380 /*
381  * tmc_sg_table_get_data: Get the buffer pointer for data @offset
382  * in the SG buffer. The @bufpp is updated to point to the buffer.
383  * Returns :
384  *	the length of linear data available at @offset.
385  *	or
386  *	<= 0 if no data is available.
387  */
388 ssize_t tmc_sg_table_get_data(struct tmc_sg_table *sg_table,
389 			      u64 offset, size_t len, char **bufpp)
390 {
391 	size_t size;
392 	int pg_idx = offset >> PAGE_SHIFT;
393 	int pg_offset = offset & (PAGE_SIZE - 1);
394 	struct tmc_pages *data_pages = &sg_table->data_pages;
395 
396 	size = tmc_sg_table_buf_size(sg_table);
397 	if (offset >= size)
398 		return -EINVAL;
399 
400 	/* Make sure we don't go beyond the end */
401 	len = (len < (size - offset)) ? len : size - offset;
402 	/* Respect the page boundaries */
403 	len = (len < (PAGE_SIZE - pg_offset)) ? len : (PAGE_SIZE - pg_offset);
404 	if (len > 0)
405 		*bufpp = page_address(data_pages->pages[pg_idx]) + pg_offset;
406 	return len;
407 }
408 EXPORT_SYMBOL_GPL(tmc_sg_table_get_data);
409 
410 #ifdef ETR_SG_DEBUG
411 /* Map a dma address to virtual address */
412 static unsigned long
413 tmc_sg_daddr_to_vaddr(struct tmc_sg_table *sg_table,
414 		      dma_addr_t addr, bool table)
415 {
416 	long offset;
417 	unsigned long base;
418 	struct tmc_pages *tmc_pages;
419 
420 	if (table) {
421 		tmc_pages = &sg_table->table_pages;
422 		base = (unsigned long)sg_table->table_vaddr;
423 	} else {
424 		tmc_pages = &sg_table->data_pages;
425 		base = (unsigned long)sg_table->data_vaddr;
426 	}
427 
428 	offset = tmc_pages_get_offset(tmc_pages, addr);
429 	if (offset < 0)
430 		return 0;
431 	return base + offset;
432 }
433 
434 /* Dump the given sg_table */
435 static void tmc_etr_sg_table_dump(struct etr_sg_table *etr_table)
436 {
437 	sgte_t *ptr;
438 	int i = 0;
439 	dma_addr_t addr;
440 	struct tmc_sg_table *sg_table = etr_table->sg_table;
441 
442 	ptr = (sgte_t *)tmc_sg_daddr_to_vaddr(sg_table,
443 					      etr_table->hwaddr, true);
444 	while (ptr) {
445 		addr = ETR_SG_ADDR(*ptr);
446 		switch (ETR_SG_ET(*ptr)) {
447 		case ETR_SG_ET_NORMAL:
448 			dev_dbg(sg_table->dev,
449 				"%05d: %p\t:[N] 0x%llx\n", i, ptr, addr);
450 			ptr++;
451 			break;
452 		case ETR_SG_ET_LINK:
453 			dev_dbg(sg_table->dev,
454 				"%05d: *** %p\t:{L} 0x%llx ***\n",
455 				 i, ptr, addr);
456 			ptr = (sgte_t *)tmc_sg_daddr_to_vaddr(sg_table,
457 							      addr, true);
458 			break;
459 		case ETR_SG_ET_LAST:
460 			dev_dbg(sg_table->dev,
461 				"%05d: ### %p\t:[L] 0x%llx ###\n",
462 				 i, ptr, addr);
463 			return;
464 		default:
465 			dev_dbg(sg_table->dev,
466 				"%05d: xxx %p\t:[INVALID] 0x%llx xxx\n",
467 				 i, ptr, addr);
468 			return;
469 		}
470 		i++;
471 	}
472 	dev_dbg(sg_table->dev, "******* End of Table *****\n");
473 }
474 #else
475 static inline void tmc_etr_sg_table_dump(struct etr_sg_table *etr_table) {}
476 #endif
477 
478 /*
479  * Populate the SG Table page table entries from table/data
480  * pages allocated. Each Data page has ETR_SG_PAGES_PER_SYSPAGE SG pages.
481  * So does a Table page. So we keep track of indices of the tables
482  * in each system page and move the pointers accordingly.
483  */
484 #define INC_IDX_ROUND(idx, size) ((idx) = ((idx) + 1) % (size))
485 static void tmc_etr_sg_table_populate(struct etr_sg_table *etr_table)
486 {
487 	dma_addr_t paddr;
488 	int i, type, nr_entries;
489 	int tpidx = 0; /* index to the current system table_page */
490 	int sgtidx = 0;	/* index to the sg_table within the current syspage */
491 	int sgtentry = 0; /* the entry within the sg_table */
492 	int dpidx = 0; /* index to the current system data_page */
493 	int spidx = 0; /* index to the SG page within the current data page */
494 	sgte_t *ptr; /* pointer to the table entry to fill */
495 	struct tmc_sg_table *sg_table = etr_table->sg_table;
496 	dma_addr_t *table_daddrs = sg_table->table_pages.daddrs;
497 	dma_addr_t *data_daddrs = sg_table->data_pages.daddrs;
498 
499 	nr_entries = tmc_etr_sg_table_entries(sg_table->data_pages.nr_pages);
500 	/*
501 	 * Use the contiguous virtual address of the table to update entries.
502 	 */
503 	ptr = sg_table->table_vaddr;
504 	/*
505 	 * Fill all the entries, except the last entry to avoid special
506 	 * checks within the loop.
507 	 */
508 	for (i = 0; i < nr_entries - 1; i++) {
509 		if (sgtentry == ETR_SG_PTRS_PER_PAGE - 1) {
510 			/*
511 			 * Last entry in a sg_table page is a link address to
512 			 * the next table page. If this sg_table is the last
513 			 * one in the system page, it links to the first
514 			 * sg_table in the next system page. Otherwise, it
515 			 * links to the next sg_table page within the system
516 			 * page.
517 			 */
518 			if (sgtidx == ETR_SG_PAGES_PER_SYSPAGE - 1) {
519 				paddr = table_daddrs[tpidx + 1];
520 			} else {
521 				paddr = table_daddrs[tpidx] +
522 					(ETR_SG_PAGE_SIZE * (sgtidx + 1));
523 			}
524 			type = ETR_SG_ET_LINK;
525 		} else {
526 			/*
527 			 * Update the indices to the data_pages to point to the
528 			 * next sg_page in the data buffer.
529 			 */
530 			type = ETR_SG_ET_NORMAL;
531 			paddr = data_daddrs[dpidx] + spidx * ETR_SG_PAGE_SIZE;
532 			if (!INC_IDX_ROUND(spidx, ETR_SG_PAGES_PER_SYSPAGE))
533 				dpidx++;
534 		}
535 		*ptr++ = ETR_SG_ENTRY(paddr, type);
536 		/*
537 		 * Move to the next table pointer, moving the table page index
538 		 * if necessary
539 		 */
540 		if (!INC_IDX_ROUND(sgtentry, ETR_SG_PTRS_PER_PAGE)) {
541 			if (!INC_IDX_ROUND(sgtidx, ETR_SG_PAGES_PER_SYSPAGE))
542 				tpidx++;
543 		}
544 	}
545 
546 	/* Set up the last entry, which is always a data pointer */
547 	paddr = data_daddrs[dpidx] + spidx * ETR_SG_PAGE_SIZE;
548 	*ptr++ = ETR_SG_ENTRY(paddr, ETR_SG_ET_LAST);
549 }
550 
551 /*
552  * tmc_init_etr_sg_table: Allocate a TMC ETR SG table, data buffer of @size and
553  * populate the table.
554  *
555  * @dev		- Device pointer for the TMC
556  * @node	- NUMA node where the memory should be allocated
557  * @size	- Total size of the data buffer
558  * @pages	- Optional list of page virtual address
559  */
560 static struct etr_sg_table *
561 tmc_init_etr_sg_table(struct device *dev, int node,
562 		      unsigned long size, void **pages)
563 {
564 	int nr_entries, nr_tpages;
565 	int nr_dpages = size >> PAGE_SHIFT;
566 	struct tmc_sg_table *sg_table;
567 	struct etr_sg_table *etr_table;
568 
569 	etr_table = kzalloc(sizeof(*etr_table), GFP_KERNEL);
570 	if (!etr_table)
571 		return ERR_PTR(-ENOMEM);
572 	nr_entries = tmc_etr_sg_table_entries(nr_dpages);
573 	nr_tpages = DIV_ROUND_UP(nr_entries, ETR_SG_PTRS_PER_SYSPAGE);
574 
575 	sg_table = tmc_alloc_sg_table(dev, node, nr_tpages, nr_dpages, pages);
576 	if (IS_ERR(sg_table)) {
577 		kfree(etr_table);
578 		return ERR_CAST(sg_table);
579 	}
580 
581 	etr_table->sg_table = sg_table;
582 	/* TMC should use table base address for DBA */
583 	etr_table->hwaddr = sg_table->table_daddr;
584 	tmc_etr_sg_table_populate(etr_table);
585 	/* Sync the table pages for the HW */
586 	tmc_sg_table_sync_table(sg_table);
587 	tmc_etr_sg_table_dump(etr_table);
588 
589 	return etr_table;
590 }
591 
592 /*
593  * tmc_etr_alloc_flat_buf: Allocate a contiguous DMA buffer.
594  */
595 static int tmc_etr_alloc_flat_buf(struct tmc_drvdata *drvdata,
596 				  struct etr_buf *etr_buf, int node,
597 				  void **pages)
598 {
599 	struct etr_flat_buf *flat_buf;
600 	struct device *real_dev = drvdata->csdev->dev.parent;
601 
602 	/* We cannot reuse existing pages for flat buf */
603 	if (pages)
604 		return -EINVAL;
605 
606 	flat_buf = kzalloc(sizeof(*flat_buf), GFP_KERNEL);
607 	if (!flat_buf)
608 		return -ENOMEM;
609 
610 	flat_buf->vaddr = dma_alloc_coherent(real_dev, etr_buf->size,
611 					     &flat_buf->daddr, GFP_KERNEL);
612 	if (!flat_buf->vaddr) {
613 		kfree(flat_buf);
614 		return -ENOMEM;
615 	}
616 
617 	flat_buf->size = etr_buf->size;
618 	flat_buf->dev = &drvdata->csdev->dev;
619 	etr_buf->hwaddr = flat_buf->daddr;
620 	etr_buf->mode = ETR_MODE_FLAT;
621 	etr_buf->private = flat_buf;
622 	return 0;
623 }
624 
625 static void tmc_etr_free_flat_buf(struct etr_buf *etr_buf)
626 {
627 	struct etr_flat_buf *flat_buf = etr_buf->private;
628 
629 	if (flat_buf && flat_buf->daddr) {
630 		struct device *real_dev = flat_buf->dev->parent;
631 
632 		dma_free_coherent(real_dev, flat_buf->size,
633 				  flat_buf->vaddr, flat_buf->daddr);
634 	}
635 	kfree(flat_buf);
636 }
637 
638 static void tmc_etr_sync_flat_buf(struct etr_buf *etr_buf, u64 rrp, u64 rwp)
639 {
640 	/*
641 	 * Adjust the buffer to point to the beginning of the trace data
642 	 * and update the available trace data.
643 	 */
644 	etr_buf->offset = rrp - etr_buf->hwaddr;
645 	if (etr_buf->full)
646 		etr_buf->len = etr_buf->size;
647 	else
648 		etr_buf->len = rwp - rrp;
649 }
650 
651 static ssize_t tmc_etr_get_data_flat_buf(struct etr_buf *etr_buf,
652 					 u64 offset, size_t len, char **bufpp)
653 {
654 	struct etr_flat_buf *flat_buf = etr_buf->private;
655 
656 	*bufpp = (char *)flat_buf->vaddr + offset;
657 	/*
658 	 * tmc_etr_buf_get_data already adjusts the length to handle
659 	 * buffer wrapping around.
660 	 */
661 	return len;
662 }
663 
664 static const struct etr_buf_operations etr_flat_buf_ops = {
665 	.alloc = tmc_etr_alloc_flat_buf,
666 	.free = tmc_etr_free_flat_buf,
667 	.sync = tmc_etr_sync_flat_buf,
668 	.get_data = tmc_etr_get_data_flat_buf,
669 };
670 
671 /*
672  * tmc_etr_alloc_sg_buf: Allocate an SG buf @etr_buf. Setup the parameters
673  * appropriately.
674  */
675 static int tmc_etr_alloc_sg_buf(struct tmc_drvdata *drvdata,
676 				struct etr_buf *etr_buf, int node,
677 				void **pages)
678 {
679 	struct etr_sg_table *etr_table;
680 	struct device *dev = &drvdata->csdev->dev;
681 
682 	etr_table = tmc_init_etr_sg_table(dev, node,
683 					  etr_buf->size, pages);
684 	if (IS_ERR(etr_table))
685 		return -ENOMEM;
686 	etr_buf->hwaddr = etr_table->hwaddr;
687 	etr_buf->mode = ETR_MODE_ETR_SG;
688 	etr_buf->private = etr_table;
689 	return 0;
690 }
691 
692 static void tmc_etr_free_sg_buf(struct etr_buf *etr_buf)
693 {
694 	struct etr_sg_table *etr_table = etr_buf->private;
695 
696 	if (etr_table) {
697 		tmc_free_sg_table(etr_table->sg_table);
698 		kfree(etr_table);
699 	}
700 }
701 
702 static ssize_t tmc_etr_get_data_sg_buf(struct etr_buf *etr_buf, u64 offset,
703 				       size_t len, char **bufpp)
704 {
705 	struct etr_sg_table *etr_table = etr_buf->private;
706 
707 	return tmc_sg_table_get_data(etr_table->sg_table, offset, len, bufpp);
708 }
709 
710 static void tmc_etr_sync_sg_buf(struct etr_buf *etr_buf, u64 rrp, u64 rwp)
711 {
712 	long r_offset, w_offset;
713 	struct etr_sg_table *etr_table = etr_buf->private;
714 	struct tmc_sg_table *table = etr_table->sg_table;
715 
716 	/* Convert hw address to offset in the buffer */
717 	r_offset = tmc_sg_get_data_page_offset(table, rrp);
718 	if (r_offset < 0) {
719 		dev_warn(table->dev,
720 			 "Unable to map RRP %llx to offset\n", rrp);
721 		etr_buf->len = 0;
722 		return;
723 	}
724 
725 	w_offset = tmc_sg_get_data_page_offset(table, rwp);
726 	if (w_offset < 0) {
727 		dev_warn(table->dev,
728 			 "Unable to map RWP %llx to offset\n", rwp);
729 		etr_buf->len = 0;
730 		return;
731 	}
732 
733 	etr_buf->offset = r_offset;
734 	if (etr_buf->full)
735 		etr_buf->len = etr_buf->size;
736 	else
737 		etr_buf->len = ((w_offset < r_offset) ? etr_buf->size : 0) +
738 				w_offset - r_offset;
739 	tmc_sg_table_sync_data_range(table, r_offset, etr_buf->len);
740 }
741 
742 static const struct etr_buf_operations etr_sg_buf_ops = {
743 	.alloc = tmc_etr_alloc_sg_buf,
744 	.free = tmc_etr_free_sg_buf,
745 	.sync = tmc_etr_sync_sg_buf,
746 	.get_data = tmc_etr_get_data_sg_buf,
747 };
748 
749 /*
750  * TMC ETR could be connected to a CATU device, which can provide address
751  * translation service. This is represented by the Output port of the TMC
752  * (ETR) connected to the input port of the CATU.
753  *
754  * Returns	: coresight_device ptr for the CATU device if a CATU is found.
755  *		: NULL otherwise.
756  */
757 struct coresight_device *
758 tmc_etr_get_catu_device(struct tmc_drvdata *drvdata)
759 {
760 	int i;
761 	struct coresight_device *tmp, *etr = drvdata->csdev;
762 
763 	if (!IS_ENABLED(CONFIG_CORESIGHT_CATU))
764 		return NULL;
765 
766 	for (i = 0; i < etr->pdata->nr_outport; i++) {
767 		tmp = etr->pdata->conns[i].child_dev;
768 		if (tmp && coresight_is_catu_device(tmp))
769 			return tmp;
770 	}
771 
772 	return NULL;
773 }
774 EXPORT_SYMBOL_GPL(tmc_etr_get_catu_device);
775 
776 static inline int tmc_etr_enable_catu(struct tmc_drvdata *drvdata,
777 				      struct etr_buf *etr_buf)
778 {
779 	struct coresight_device *catu = tmc_etr_get_catu_device(drvdata);
780 
781 	if (catu && helper_ops(catu)->enable)
782 		return helper_ops(catu)->enable(catu, etr_buf);
783 	return 0;
784 }
785 
786 static inline void tmc_etr_disable_catu(struct tmc_drvdata *drvdata)
787 {
788 	struct coresight_device *catu = tmc_etr_get_catu_device(drvdata);
789 
790 	if (catu && helper_ops(catu)->disable)
791 		helper_ops(catu)->disable(catu, drvdata->etr_buf);
792 }
793 
794 static const struct etr_buf_operations *etr_buf_ops[] = {
795 	[ETR_MODE_FLAT] = &etr_flat_buf_ops,
796 	[ETR_MODE_ETR_SG] = &etr_sg_buf_ops,
797 	[ETR_MODE_CATU] = NULL,
798 };
799 
800 void tmc_etr_set_catu_ops(const struct etr_buf_operations *catu)
801 {
802 	etr_buf_ops[ETR_MODE_CATU] = catu;
803 }
804 EXPORT_SYMBOL_GPL(tmc_etr_set_catu_ops);
805 
806 void tmc_etr_remove_catu_ops(void)
807 {
808 	etr_buf_ops[ETR_MODE_CATU] = NULL;
809 }
810 EXPORT_SYMBOL_GPL(tmc_etr_remove_catu_ops);
811 
812 static inline int tmc_etr_mode_alloc_buf(int mode,
813 					 struct tmc_drvdata *drvdata,
814 					 struct etr_buf *etr_buf, int node,
815 					 void **pages)
816 {
817 	int rc = -EINVAL;
818 
819 	switch (mode) {
820 	case ETR_MODE_FLAT:
821 	case ETR_MODE_ETR_SG:
822 	case ETR_MODE_CATU:
823 		if (etr_buf_ops[mode] && etr_buf_ops[mode]->alloc)
824 			rc = etr_buf_ops[mode]->alloc(drvdata, etr_buf,
825 						      node, pages);
826 		if (!rc)
827 			etr_buf->ops = etr_buf_ops[mode];
828 		return rc;
829 	default:
830 		return -EINVAL;
831 	}
832 }
833 
834 /*
835  * tmc_alloc_etr_buf: Allocate a buffer use by ETR.
836  * @drvdata	: ETR device details.
837  * @size	: size of the requested buffer.
838  * @flags	: Required properties for the buffer.
839  * @node	: Node for memory allocations.
840  * @pages	: An optional list of pages.
841  */
842 static struct etr_buf *tmc_alloc_etr_buf(struct tmc_drvdata *drvdata,
843 					 ssize_t size, int flags,
844 					 int node, void **pages)
845 {
846 	int rc = -ENOMEM;
847 	bool has_etr_sg, has_iommu;
848 	bool has_sg, has_catu;
849 	struct etr_buf *etr_buf;
850 	struct device *dev = &drvdata->csdev->dev;
851 
852 	has_etr_sg = tmc_etr_has_cap(drvdata, TMC_ETR_SG);
853 	has_iommu = iommu_get_domain_for_dev(dev->parent);
854 	has_catu = !!tmc_etr_get_catu_device(drvdata);
855 
856 	has_sg = has_catu || has_etr_sg;
857 
858 	etr_buf = kzalloc(sizeof(*etr_buf), GFP_KERNEL);
859 	if (!etr_buf)
860 		return ERR_PTR(-ENOMEM);
861 
862 	etr_buf->size = size;
863 
864 	/*
865 	 * If we have to use an existing list of pages, we cannot reliably
866 	 * use a contiguous DMA memory (even if we have an IOMMU). Otherwise,
867 	 * we use the contiguous DMA memory if at least one of the following
868 	 * conditions is true:
869 	 *  a) The ETR cannot use Scatter-Gather.
870 	 *  b) we have a backing IOMMU
871 	 *  c) The requested memory size is smaller (< 1M).
872 	 *
873 	 * Fallback to available mechanisms.
874 	 *
875 	 */
876 	if (!pages &&
877 	    (!has_sg || has_iommu || size < SZ_1M))
878 		rc = tmc_etr_mode_alloc_buf(ETR_MODE_FLAT, drvdata,
879 					    etr_buf, node, pages);
880 	if (rc && has_etr_sg)
881 		rc = tmc_etr_mode_alloc_buf(ETR_MODE_ETR_SG, drvdata,
882 					    etr_buf, node, pages);
883 	if (rc && has_catu)
884 		rc = tmc_etr_mode_alloc_buf(ETR_MODE_CATU, drvdata,
885 					    etr_buf, node, pages);
886 	if (rc) {
887 		kfree(etr_buf);
888 		return ERR_PTR(rc);
889 	}
890 
891 	refcount_set(&etr_buf->refcount, 1);
892 	dev_dbg(dev, "allocated buffer of size %ldKB in mode %d\n",
893 		(unsigned long)size >> 10, etr_buf->mode);
894 	return etr_buf;
895 }
896 
897 static void tmc_free_etr_buf(struct etr_buf *etr_buf)
898 {
899 	WARN_ON(!etr_buf->ops || !etr_buf->ops->free);
900 	etr_buf->ops->free(etr_buf);
901 	kfree(etr_buf);
902 }
903 
904 /*
905  * tmc_etr_buf_get_data: Get the pointer the trace data at @offset
906  * with a maximum of @len bytes.
907  * Returns: The size of the linear data available @pos, with *bufpp
908  * updated to point to the buffer.
909  */
910 static ssize_t tmc_etr_buf_get_data(struct etr_buf *etr_buf,
911 				    u64 offset, size_t len, char **bufpp)
912 {
913 	/* Adjust the length to limit this transaction to end of buffer */
914 	len = (len < (etr_buf->size - offset)) ? len : etr_buf->size - offset;
915 
916 	return etr_buf->ops->get_data(etr_buf, (u64)offset, len, bufpp);
917 }
918 
919 static inline s64
920 tmc_etr_buf_insert_barrier_packet(struct etr_buf *etr_buf, u64 offset)
921 {
922 	ssize_t len;
923 	char *bufp;
924 
925 	len = tmc_etr_buf_get_data(etr_buf, offset,
926 				   CORESIGHT_BARRIER_PKT_SIZE, &bufp);
927 	if (WARN_ON(len < CORESIGHT_BARRIER_PKT_SIZE))
928 		return -EINVAL;
929 	coresight_insert_barrier_packet(bufp);
930 	return offset + CORESIGHT_BARRIER_PKT_SIZE;
931 }
932 
933 /*
934  * tmc_sync_etr_buf: Sync the trace buffer availability with drvdata.
935  * Makes sure the trace data is synced to the memory for consumption.
936  * @etr_buf->offset will hold the offset to the beginning of the trace data
937  * within the buffer, with @etr_buf->len bytes to consume.
938  */
939 static void tmc_sync_etr_buf(struct tmc_drvdata *drvdata)
940 {
941 	struct etr_buf *etr_buf = drvdata->etr_buf;
942 	u64 rrp, rwp;
943 	u32 status;
944 
945 	rrp = tmc_read_rrp(drvdata);
946 	rwp = tmc_read_rwp(drvdata);
947 	status = readl_relaxed(drvdata->base + TMC_STS);
948 
949 	/*
950 	 * If there were memory errors in the session, truncate the
951 	 * buffer.
952 	 */
953 	if (WARN_ON_ONCE(status & TMC_STS_MEMERR)) {
954 		dev_dbg(&drvdata->csdev->dev,
955 			"tmc memory error detected, truncating buffer\n");
956 		etr_buf->len = 0;
957 		etr_buf->full = 0;
958 		return;
959 	}
960 
961 	etr_buf->full = status & TMC_STS_FULL;
962 
963 	WARN_ON(!etr_buf->ops || !etr_buf->ops->sync);
964 
965 	etr_buf->ops->sync(etr_buf, rrp, rwp);
966 }
967 
968 static void __tmc_etr_enable_hw(struct tmc_drvdata *drvdata)
969 {
970 	u32 axictl, sts;
971 	struct etr_buf *etr_buf = drvdata->etr_buf;
972 
973 	CS_UNLOCK(drvdata->base);
974 
975 	/* Wait for TMCSReady bit to be set */
976 	tmc_wait_for_tmcready(drvdata);
977 
978 	writel_relaxed(etr_buf->size / 4, drvdata->base + TMC_RSZ);
979 	writel_relaxed(TMC_MODE_CIRCULAR_BUFFER, drvdata->base + TMC_MODE);
980 
981 	axictl = readl_relaxed(drvdata->base + TMC_AXICTL);
982 	axictl &= ~TMC_AXICTL_CLEAR_MASK;
983 	axictl |= (TMC_AXICTL_PROT_CTL_B1 | TMC_AXICTL_WR_BURST_16);
984 	axictl |= TMC_AXICTL_AXCACHE_OS;
985 
986 	if (tmc_etr_has_cap(drvdata, TMC_ETR_AXI_ARCACHE)) {
987 		axictl &= ~TMC_AXICTL_ARCACHE_MASK;
988 		axictl |= TMC_AXICTL_ARCACHE_OS;
989 	}
990 
991 	if (etr_buf->mode == ETR_MODE_ETR_SG)
992 		axictl |= TMC_AXICTL_SCT_GAT_MODE;
993 
994 	writel_relaxed(axictl, drvdata->base + TMC_AXICTL);
995 	tmc_write_dba(drvdata, etr_buf->hwaddr);
996 	/*
997 	 * If the TMC pointers must be programmed before the session,
998 	 * we have to set it properly (i.e, RRP/RWP to base address and
999 	 * STS to "not full").
1000 	 */
1001 	if (tmc_etr_has_cap(drvdata, TMC_ETR_SAVE_RESTORE)) {
1002 		tmc_write_rrp(drvdata, etr_buf->hwaddr);
1003 		tmc_write_rwp(drvdata, etr_buf->hwaddr);
1004 		sts = readl_relaxed(drvdata->base + TMC_STS) & ~TMC_STS_FULL;
1005 		writel_relaxed(sts, drvdata->base + TMC_STS);
1006 	}
1007 
1008 	writel_relaxed(TMC_FFCR_EN_FMT | TMC_FFCR_EN_TI |
1009 		       TMC_FFCR_FON_FLIN | TMC_FFCR_FON_TRIG_EVT |
1010 		       TMC_FFCR_TRIGON_TRIGIN,
1011 		       drvdata->base + TMC_FFCR);
1012 	writel_relaxed(drvdata->trigger_cntr, drvdata->base + TMC_TRG);
1013 	tmc_enable_hw(drvdata);
1014 
1015 	CS_LOCK(drvdata->base);
1016 }
1017 
1018 static int tmc_etr_enable_hw(struct tmc_drvdata *drvdata,
1019 			     struct etr_buf *etr_buf)
1020 {
1021 	int rc;
1022 
1023 	/* Callers should provide an appropriate buffer for use */
1024 	if (WARN_ON(!etr_buf))
1025 		return -EINVAL;
1026 
1027 	if ((etr_buf->mode == ETR_MODE_ETR_SG) &&
1028 	    WARN_ON(!tmc_etr_has_cap(drvdata, TMC_ETR_SG)))
1029 		return -EINVAL;
1030 
1031 	if (WARN_ON(drvdata->etr_buf))
1032 		return -EBUSY;
1033 
1034 	/*
1035 	 * If this ETR is connected to a CATU, enable it before we turn
1036 	 * this on.
1037 	 */
1038 	rc = tmc_etr_enable_catu(drvdata, etr_buf);
1039 	if (rc)
1040 		return rc;
1041 	rc = coresight_claim_device(drvdata->base);
1042 	if (!rc) {
1043 		drvdata->etr_buf = etr_buf;
1044 		__tmc_etr_enable_hw(drvdata);
1045 	}
1046 
1047 	return rc;
1048 }
1049 
1050 /*
1051  * Return the available trace data in the buffer (starts at etr_buf->offset,
1052  * limited by etr_buf->len) from @pos, with a maximum limit of @len,
1053  * also updating the @bufpp on where to find it. Since the trace data
1054  * starts at anywhere in the buffer, depending on the RRP, we adjust the
1055  * @len returned to handle buffer wrapping around.
1056  *
1057  * We are protected here by drvdata->reading != 0, which ensures the
1058  * sysfs_buf stays alive.
1059  */
1060 ssize_t tmc_etr_get_sysfs_trace(struct tmc_drvdata *drvdata,
1061 				loff_t pos, size_t len, char **bufpp)
1062 {
1063 	s64 offset;
1064 	ssize_t actual = len;
1065 	struct etr_buf *etr_buf = drvdata->sysfs_buf;
1066 
1067 	if (pos + actual > etr_buf->len)
1068 		actual = etr_buf->len - pos;
1069 	if (actual <= 0)
1070 		return actual;
1071 
1072 	/* Compute the offset from which we read the data */
1073 	offset = etr_buf->offset + pos;
1074 	if (offset >= etr_buf->size)
1075 		offset -= etr_buf->size;
1076 	return tmc_etr_buf_get_data(etr_buf, offset, actual, bufpp);
1077 }
1078 
1079 static struct etr_buf *
1080 tmc_etr_setup_sysfs_buf(struct tmc_drvdata *drvdata)
1081 {
1082 	return tmc_alloc_etr_buf(drvdata, drvdata->size,
1083 				 0, cpu_to_node(0), NULL);
1084 }
1085 
1086 static void
1087 tmc_etr_free_sysfs_buf(struct etr_buf *buf)
1088 {
1089 	if (buf)
1090 		tmc_free_etr_buf(buf);
1091 }
1092 
1093 static void tmc_etr_sync_sysfs_buf(struct tmc_drvdata *drvdata)
1094 {
1095 	struct etr_buf *etr_buf = drvdata->etr_buf;
1096 
1097 	if (WARN_ON(drvdata->sysfs_buf != etr_buf)) {
1098 		tmc_etr_free_sysfs_buf(drvdata->sysfs_buf);
1099 		drvdata->sysfs_buf = NULL;
1100 	} else {
1101 		tmc_sync_etr_buf(drvdata);
1102 		/*
1103 		 * Insert barrier packets at the beginning, if there was
1104 		 * an overflow.
1105 		 */
1106 		if (etr_buf->full)
1107 			tmc_etr_buf_insert_barrier_packet(etr_buf,
1108 							  etr_buf->offset);
1109 	}
1110 }
1111 
1112 static void __tmc_etr_disable_hw(struct tmc_drvdata *drvdata)
1113 {
1114 	CS_UNLOCK(drvdata->base);
1115 
1116 	tmc_flush_and_stop(drvdata);
1117 	/*
1118 	 * When operating in sysFS mode the content of the buffer needs to be
1119 	 * read before the TMC is disabled.
1120 	 */
1121 	if (drvdata->mode == CS_MODE_SYSFS)
1122 		tmc_etr_sync_sysfs_buf(drvdata);
1123 
1124 	tmc_disable_hw(drvdata);
1125 
1126 	CS_LOCK(drvdata->base);
1127 
1128 }
1129 
1130 void tmc_etr_disable_hw(struct tmc_drvdata *drvdata)
1131 {
1132 	__tmc_etr_disable_hw(drvdata);
1133 	/* Disable CATU device if this ETR is connected to one */
1134 	tmc_etr_disable_catu(drvdata);
1135 	coresight_disclaim_device(drvdata->base);
1136 	/* Reset the ETR buf used by hardware */
1137 	drvdata->etr_buf = NULL;
1138 }
1139 
1140 static int tmc_enable_etr_sink_sysfs(struct coresight_device *csdev)
1141 {
1142 	int ret = 0;
1143 	unsigned long flags;
1144 	struct tmc_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
1145 	struct etr_buf *sysfs_buf = NULL, *new_buf = NULL, *free_buf = NULL;
1146 
1147 	/*
1148 	 * If we are enabling the ETR from disabled state, we need to make
1149 	 * sure we have a buffer with the right size. The etr_buf is not reset
1150 	 * immediately after we stop the tracing in SYSFS mode as we wait for
1151 	 * the user to collect the data. We may be able to reuse the existing
1152 	 * buffer, provided the size matches. Any allocation has to be done
1153 	 * with the lock released.
1154 	 */
1155 	spin_lock_irqsave(&drvdata->spinlock, flags);
1156 	sysfs_buf = READ_ONCE(drvdata->sysfs_buf);
1157 	if (!sysfs_buf || (sysfs_buf->size != drvdata->size)) {
1158 		spin_unlock_irqrestore(&drvdata->spinlock, flags);
1159 
1160 		/* Allocate memory with the locks released */
1161 		free_buf = new_buf = tmc_etr_setup_sysfs_buf(drvdata);
1162 		if (IS_ERR(new_buf))
1163 			return PTR_ERR(new_buf);
1164 
1165 		/* Let's try again */
1166 		spin_lock_irqsave(&drvdata->spinlock, flags);
1167 	}
1168 
1169 	if (drvdata->reading || drvdata->mode == CS_MODE_PERF) {
1170 		ret = -EBUSY;
1171 		goto out;
1172 	}
1173 
1174 	/*
1175 	 * In sysFS mode we can have multiple writers per sink.  Since this
1176 	 * sink is already enabled no memory is needed and the HW need not be
1177 	 * touched, even if the buffer size has changed.
1178 	 */
1179 	if (drvdata->mode == CS_MODE_SYSFS) {
1180 		atomic_inc(csdev->refcnt);
1181 		goto out;
1182 	}
1183 
1184 	/*
1185 	 * If we don't have a buffer or it doesn't match the requested size,
1186 	 * use the buffer allocated above. Otherwise reuse the existing buffer.
1187 	 */
1188 	sysfs_buf = READ_ONCE(drvdata->sysfs_buf);
1189 	if (!sysfs_buf || (new_buf && sysfs_buf->size != new_buf->size)) {
1190 		free_buf = sysfs_buf;
1191 		drvdata->sysfs_buf = new_buf;
1192 	}
1193 
1194 	ret = tmc_etr_enable_hw(drvdata, drvdata->sysfs_buf);
1195 	if (!ret) {
1196 		drvdata->mode = CS_MODE_SYSFS;
1197 		atomic_inc(csdev->refcnt);
1198 	}
1199 out:
1200 	spin_unlock_irqrestore(&drvdata->spinlock, flags);
1201 
1202 	/* Free memory outside the spinlock if need be */
1203 	if (free_buf)
1204 		tmc_etr_free_sysfs_buf(free_buf);
1205 
1206 	if (!ret)
1207 		dev_dbg(&csdev->dev, "TMC-ETR enabled\n");
1208 
1209 	return ret;
1210 }
1211 
1212 /*
1213  * alloc_etr_buf: Allocate ETR buffer for use by perf.
1214  * The size of the hardware buffer is dependent on the size configured
1215  * via sysfs and the perf ring buffer size. We prefer to allocate the
1216  * largest possible size, scaling down the size by half until it
1217  * reaches a minimum limit (1M), beyond which we give up.
1218  */
1219 static struct etr_buf *
1220 alloc_etr_buf(struct tmc_drvdata *drvdata, struct perf_event *event,
1221 	      int nr_pages, void **pages, bool snapshot)
1222 {
1223 	int node;
1224 	struct etr_buf *etr_buf;
1225 	unsigned long size;
1226 
1227 	node = (event->cpu == -1) ? NUMA_NO_NODE : cpu_to_node(event->cpu);
1228 	/*
1229 	 * Try to match the perf ring buffer size if it is larger
1230 	 * than the size requested via sysfs.
1231 	 */
1232 	if ((nr_pages << PAGE_SHIFT) > drvdata->size) {
1233 		etr_buf = tmc_alloc_etr_buf(drvdata, (nr_pages << PAGE_SHIFT),
1234 					    0, node, NULL);
1235 		if (!IS_ERR(etr_buf))
1236 			goto done;
1237 	}
1238 
1239 	/*
1240 	 * Else switch to configured size for this ETR
1241 	 * and scale down until we hit the minimum limit.
1242 	 */
1243 	size = drvdata->size;
1244 	do {
1245 		etr_buf = tmc_alloc_etr_buf(drvdata, size, 0, node, NULL);
1246 		if (!IS_ERR(etr_buf))
1247 			goto done;
1248 		size /= 2;
1249 	} while (size >= TMC_ETR_PERF_MIN_BUF_SIZE);
1250 
1251 	return ERR_PTR(-ENOMEM);
1252 
1253 done:
1254 	return etr_buf;
1255 }
1256 
1257 static struct etr_buf *
1258 get_perf_etr_buf_cpu_wide(struct tmc_drvdata *drvdata,
1259 			  struct perf_event *event, int nr_pages,
1260 			  void **pages, bool snapshot)
1261 {
1262 	int ret;
1263 	pid_t pid = task_pid_nr(event->owner);
1264 	struct etr_buf *etr_buf;
1265 
1266 retry:
1267 	/*
1268 	 * An etr_perf_buffer is associated with an event and holds a reference
1269 	 * to the AUX ring buffer that was created for that event.  In CPU-wide
1270 	 * N:1 mode multiple events (one per CPU), each with its own AUX ring
1271 	 * buffer, share a sink.  As such an etr_perf_buffer is created for each
1272 	 * event but a single etr_buf associated with the ETR is shared between
1273 	 * them.  The last event in a trace session will copy the content of the
1274 	 * etr_buf to its AUX ring buffer.  Ring buffer associated to other
1275 	 * events are simply not used an freed as events are destoyed.  We still
1276 	 * need to allocate a ring buffer for each event since we don't know
1277 	 * which event will be last.
1278 	 */
1279 
1280 	/*
1281 	 * The first thing to do here is check if an etr_buf has already been
1282 	 * allocated for this session.  If so it is shared with this event,
1283 	 * otherwise it is created.
1284 	 */
1285 	mutex_lock(&drvdata->idr_mutex);
1286 	etr_buf = idr_find(&drvdata->idr, pid);
1287 	if (etr_buf) {
1288 		refcount_inc(&etr_buf->refcount);
1289 		mutex_unlock(&drvdata->idr_mutex);
1290 		return etr_buf;
1291 	}
1292 
1293 	/* If we made it here no buffer has been allocated, do so now. */
1294 	mutex_unlock(&drvdata->idr_mutex);
1295 
1296 	etr_buf = alloc_etr_buf(drvdata, event, nr_pages, pages, snapshot);
1297 	if (IS_ERR(etr_buf))
1298 		return etr_buf;
1299 
1300 	/* Now that we have a buffer, add it to the IDR. */
1301 	mutex_lock(&drvdata->idr_mutex);
1302 	ret = idr_alloc(&drvdata->idr, etr_buf, pid, pid + 1, GFP_KERNEL);
1303 	mutex_unlock(&drvdata->idr_mutex);
1304 
1305 	/* Another event with this session ID has allocated this buffer. */
1306 	if (ret == -ENOSPC) {
1307 		tmc_free_etr_buf(etr_buf);
1308 		goto retry;
1309 	}
1310 
1311 	/* The IDR can't allocate room for a new session, abandon ship. */
1312 	if (ret == -ENOMEM) {
1313 		tmc_free_etr_buf(etr_buf);
1314 		return ERR_PTR(ret);
1315 	}
1316 
1317 
1318 	return etr_buf;
1319 }
1320 
1321 static struct etr_buf *
1322 get_perf_etr_buf_per_thread(struct tmc_drvdata *drvdata,
1323 			    struct perf_event *event, int nr_pages,
1324 			    void **pages, bool snapshot)
1325 {
1326 	/*
1327 	 * In per-thread mode the etr_buf isn't shared, so just go ahead
1328 	 * with memory allocation.
1329 	 */
1330 	return alloc_etr_buf(drvdata, event, nr_pages, pages, snapshot);
1331 }
1332 
1333 static struct etr_buf *
1334 get_perf_etr_buf(struct tmc_drvdata *drvdata, struct perf_event *event,
1335 		 int nr_pages, void **pages, bool snapshot)
1336 {
1337 	if (event->cpu == -1)
1338 		return get_perf_etr_buf_per_thread(drvdata, event, nr_pages,
1339 						   pages, snapshot);
1340 
1341 	return get_perf_etr_buf_cpu_wide(drvdata, event, nr_pages,
1342 					 pages, snapshot);
1343 }
1344 
1345 static struct etr_perf_buffer *
1346 tmc_etr_setup_perf_buf(struct tmc_drvdata *drvdata, struct perf_event *event,
1347 		       int nr_pages, void **pages, bool snapshot)
1348 {
1349 	int node;
1350 	struct etr_buf *etr_buf;
1351 	struct etr_perf_buffer *etr_perf;
1352 
1353 	node = (event->cpu == -1) ? NUMA_NO_NODE : cpu_to_node(event->cpu);
1354 
1355 	etr_perf = kzalloc_node(sizeof(*etr_perf), GFP_KERNEL, node);
1356 	if (!etr_perf)
1357 		return ERR_PTR(-ENOMEM);
1358 
1359 	etr_buf = get_perf_etr_buf(drvdata, event, nr_pages, pages, snapshot);
1360 	if (!IS_ERR(etr_buf))
1361 		goto done;
1362 
1363 	kfree(etr_perf);
1364 	return ERR_PTR(-ENOMEM);
1365 
1366 done:
1367 	/*
1368 	 * Keep a reference to the ETR this buffer has been allocated for
1369 	 * in order to have access to the IDR in tmc_free_etr_buffer().
1370 	 */
1371 	etr_perf->drvdata = drvdata;
1372 	etr_perf->etr_buf = etr_buf;
1373 
1374 	return etr_perf;
1375 }
1376 
1377 
1378 static void *tmc_alloc_etr_buffer(struct coresight_device *csdev,
1379 				  struct perf_event *event, void **pages,
1380 				  int nr_pages, bool snapshot)
1381 {
1382 	struct etr_perf_buffer *etr_perf;
1383 	struct tmc_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
1384 
1385 	etr_perf = tmc_etr_setup_perf_buf(drvdata, event,
1386 					  nr_pages, pages, snapshot);
1387 	if (IS_ERR(etr_perf)) {
1388 		dev_dbg(&csdev->dev, "Unable to allocate ETR buffer\n");
1389 		return NULL;
1390 	}
1391 
1392 	etr_perf->pid = task_pid_nr(event->owner);
1393 	etr_perf->snapshot = snapshot;
1394 	etr_perf->nr_pages = nr_pages;
1395 	etr_perf->pages = pages;
1396 
1397 	return etr_perf;
1398 }
1399 
1400 static void tmc_free_etr_buffer(void *config)
1401 {
1402 	struct etr_perf_buffer *etr_perf = config;
1403 	struct tmc_drvdata *drvdata = etr_perf->drvdata;
1404 	struct etr_buf *buf, *etr_buf = etr_perf->etr_buf;
1405 
1406 	if (!etr_buf)
1407 		goto free_etr_perf_buffer;
1408 
1409 	mutex_lock(&drvdata->idr_mutex);
1410 	/* If we are not the last one to use the buffer, don't touch it. */
1411 	if (!refcount_dec_and_test(&etr_buf->refcount)) {
1412 		mutex_unlock(&drvdata->idr_mutex);
1413 		goto free_etr_perf_buffer;
1414 	}
1415 
1416 	/* We are the last one, remove from the IDR and free the buffer. */
1417 	buf = idr_remove(&drvdata->idr, etr_perf->pid);
1418 	mutex_unlock(&drvdata->idr_mutex);
1419 
1420 	/*
1421 	 * Something went very wrong if the buffer associated with this ID
1422 	 * is not the same in the IDR.  Leak to avoid use after free.
1423 	 */
1424 	if (buf && WARN_ON(buf != etr_buf))
1425 		goto free_etr_perf_buffer;
1426 
1427 	tmc_free_etr_buf(etr_perf->etr_buf);
1428 
1429 free_etr_perf_buffer:
1430 	kfree(etr_perf);
1431 }
1432 
1433 /*
1434  * tmc_etr_sync_perf_buffer: Copy the actual trace data from the hardware
1435  * buffer to the perf ring buffer.
1436  */
1437 static void tmc_etr_sync_perf_buffer(struct etr_perf_buffer *etr_perf,
1438 				     unsigned long src_offset,
1439 				     unsigned long to_copy)
1440 {
1441 	long bytes;
1442 	long pg_idx, pg_offset;
1443 	unsigned long head = etr_perf->head;
1444 	char **dst_pages, *src_buf;
1445 	struct etr_buf *etr_buf = etr_perf->etr_buf;
1446 
1447 	head = etr_perf->head;
1448 	pg_idx = head >> PAGE_SHIFT;
1449 	pg_offset = head & (PAGE_SIZE - 1);
1450 	dst_pages = (char **)etr_perf->pages;
1451 
1452 	while (to_copy > 0) {
1453 		/*
1454 		 * In one iteration, we can copy minimum of :
1455 		 *  1) what is available in the source buffer,
1456 		 *  2) what is available in the source buffer, before it
1457 		 *     wraps around.
1458 		 *  3) what is available in the destination page.
1459 		 * in one iteration.
1460 		 */
1461 		if (src_offset >= etr_buf->size)
1462 			src_offset -= etr_buf->size;
1463 		bytes = tmc_etr_buf_get_data(etr_buf, src_offset, to_copy,
1464 					     &src_buf);
1465 		if (WARN_ON_ONCE(bytes <= 0))
1466 			break;
1467 		bytes = min(bytes, (long)(PAGE_SIZE - pg_offset));
1468 
1469 		memcpy(dst_pages[pg_idx] + pg_offset, src_buf, bytes);
1470 
1471 		to_copy -= bytes;
1472 
1473 		/* Move destination pointers */
1474 		pg_offset += bytes;
1475 		if (pg_offset == PAGE_SIZE) {
1476 			pg_offset = 0;
1477 			if (++pg_idx == etr_perf->nr_pages)
1478 				pg_idx = 0;
1479 		}
1480 
1481 		/* Move source pointers */
1482 		src_offset += bytes;
1483 	}
1484 }
1485 
1486 /*
1487  * tmc_update_etr_buffer : Update the perf ring buffer with the
1488  * available trace data. We use software double buffering at the moment.
1489  *
1490  * TODO: Add support for reusing the perf ring buffer.
1491  */
1492 static unsigned long
1493 tmc_update_etr_buffer(struct coresight_device *csdev,
1494 		      struct perf_output_handle *handle,
1495 		      void *config)
1496 {
1497 	bool lost = false;
1498 	unsigned long flags, offset, size = 0;
1499 	struct tmc_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
1500 	struct etr_perf_buffer *etr_perf = config;
1501 	struct etr_buf *etr_buf = etr_perf->etr_buf;
1502 
1503 	spin_lock_irqsave(&drvdata->spinlock, flags);
1504 
1505 	/* Don't do anything if another tracer is using this sink */
1506 	if (atomic_read(csdev->refcnt) != 1) {
1507 		spin_unlock_irqrestore(&drvdata->spinlock, flags);
1508 		goto out;
1509 	}
1510 
1511 	if (WARN_ON(drvdata->perf_buf != etr_buf)) {
1512 		lost = true;
1513 		spin_unlock_irqrestore(&drvdata->spinlock, flags);
1514 		goto out;
1515 	}
1516 
1517 	CS_UNLOCK(drvdata->base);
1518 
1519 	tmc_flush_and_stop(drvdata);
1520 	tmc_sync_etr_buf(drvdata);
1521 
1522 	CS_LOCK(drvdata->base);
1523 	spin_unlock_irqrestore(&drvdata->spinlock, flags);
1524 
1525 	lost = etr_buf->full;
1526 	offset = etr_buf->offset;
1527 	size = etr_buf->len;
1528 
1529 	/*
1530 	 * The ETR buffer may be bigger than the space available in the
1531 	 * perf ring buffer (handle->size).  If so advance the offset so that we
1532 	 * get the latest trace data.  In snapshot mode none of that matters
1533 	 * since we are expected to clobber stale data in favour of the latest
1534 	 * traces.
1535 	 */
1536 	if (!etr_perf->snapshot && size > handle->size) {
1537 		u32 mask = tmc_get_memwidth_mask(drvdata);
1538 
1539 		/*
1540 		 * Make sure the new size is aligned in accordance with the
1541 		 * requirement explained in function tmc_get_memwidth_mask().
1542 		 */
1543 		size = handle->size & mask;
1544 		offset = etr_buf->offset + etr_buf->len - size;
1545 
1546 		if (offset >= etr_buf->size)
1547 			offset -= etr_buf->size;
1548 		lost = true;
1549 	}
1550 
1551 	/* Insert barrier packets at the beginning, if there was an overflow */
1552 	if (lost)
1553 		tmc_etr_buf_insert_barrier_packet(etr_buf, etr_buf->offset);
1554 	tmc_etr_sync_perf_buffer(etr_perf, offset, size);
1555 
1556 	/*
1557 	 * In snapshot mode we simply increment the head by the number of byte
1558 	 * that were written.  User space function  cs_etm_find_snapshot() will
1559 	 * figure out how many bytes to get from the AUX buffer based on the
1560 	 * position of the head.
1561 	 */
1562 	if (etr_perf->snapshot)
1563 		handle->head += size;
1564 out:
1565 	/*
1566 	 * Don't set the TRUNCATED flag in snapshot mode because 1) the
1567 	 * captured buffer is expected to be truncated and 2) a full buffer
1568 	 * prevents the event from being re-enabled by the perf core,
1569 	 * resulting in stale data being send to user space.
1570 	 */
1571 	if (!etr_perf->snapshot && lost)
1572 		perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED);
1573 	return size;
1574 }
1575 
1576 static int tmc_enable_etr_sink_perf(struct coresight_device *csdev, void *data)
1577 {
1578 	int rc = 0;
1579 	pid_t pid;
1580 	unsigned long flags;
1581 	struct tmc_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
1582 	struct perf_output_handle *handle = data;
1583 	struct etr_perf_buffer *etr_perf = etm_perf_sink_config(handle);
1584 
1585 	spin_lock_irqsave(&drvdata->spinlock, flags);
1586 	 /* Don't use this sink if it is already claimed by sysFS */
1587 	if (drvdata->mode == CS_MODE_SYSFS) {
1588 		rc = -EBUSY;
1589 		goto unlock_out;
1590 	}
1591 
1592 	if (WARN_ON(!etr_perf || !etr_perf->etr_buf)) {
1593 		rc = -EINVAL;
1594 		goto unlock_out;
1595 	}
1596 
1597 	/* Get a handle on the pid of the process to monitor */
1598 	pid = etr_perf->pid;
1599 
1600 	/* Do not proceed if this device is associated with another session */
1601 	if (drvdata->pid != -1 && drvdata->pid != pid) {
1602 		rc = -EBUSY;
1603 		goto unlock_out;
1604 	}
1605 
1606 	etr_perf->head = PERF_IDX2OFF(handle->head, etr_perf);
1607 
1608 	/*
1609 	 * No HW configuration is needed if the sink is already in
1610 	 * use for this session.
1611 	 */
1612 	if (drvdata->pid == pid) {
1613 		atomic_inc(csdev->refcnt);
1614 		goto unlock_out;
1615 	}
1616 
1617 	rc = tmc_etr_enable_hw(drvdata, etr_perf->etr_buf);
1618 	if (!rc) {
1619 		/* Associate with monitored process. */
1620 		drvdata->pid = pid;
1621 		drvdata->mode = CS_MODE_PERF;
1622 		drvdata->perf_buf = etr_perf->etr_buf;
1623 		atomic_inc(csdev->refcnt);
1624 	}
1625 
1626 unlock_out:
1627 	spin_unlock_irqrestore(&drvdata->spinlock, flags);
1628 	return rc;
1629 }
1630 
1631 static int tmc_enable_etr_sink(struct coresight_device *csdev,
1632 			       u32 mode, void *data)
1633 {
1634 	switch (mode) {
1635 	case CS_MODE_SYSFS:
1636 		return tmc_enable_etr_sink_sysfs(csdev);
1637 	case CS_MODE_PERF:
1638 		return tmc_enable_etr_sink_perf(csdev, data);
1639 	}
1640 
1641 	/* We shouldn't be here */
1642 	return -EINVAL;
1643 }
1644 
1645 static int tmc_disable_etr_sink(struct coresight_device *csdev)
1646 {
1647 	unsigned long flags;
1648 	struct tmc_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent);
1649 
1650 	spin_lock_irqsave(&drvdata->spinlock, flags);
1651 
1652 	if (drvdata->reading) {
1653 		spin_unlock_irqrestore(&drvdata->spinlock, flags);
1654 		return -EBUSY;
1655 	}
1656 
1657 	if (atomic_dec_return(csdev->refcnt)) {
1658 		spin_unlock_irqrestore(&drvdata->spinlock, flags);
1659 		return -EBUSY;
1660 	}
1661 
1662 	/* Complain if we (somehow) got out of sync */
1663 	WARN_ON_ONCE(drvdata->mode == CS_MODE_DISABLED);
1664 	tmc_etr_disable_hw(drvdata);
1665 	/* Dissociate from monitored process. */
1666 	drvdata->pid = -1;
1667 	drvdata->mode = CS_MODE_DISABLED;
1668 	/* Reset perf specific data */
1669 	drvdata->perf_buf = NULL;
1670 
1671 	spin_unlock_irqrestore(&drvdata->spinlock, flags);
1672 
1673 	dev_dbg(&csdev->dev, "TMC-ETR disabled\n");
1674 	return 0;
1675 }
1676 
1677 static const struct coresight_ops_sink tmc_etr_sink_ops = {
1678 	.enable		= tmc_enable_etr_sink,
1679 	.disable	= tmc_disable_etr_sink,
1680 	.alloc_buffer	= tmc_alloc_etr_buffer,
1681 	.update_buffer	= tmc_update_etr_buffer,
1682 	.free_buffer	= tmc_free_etr_buffer,
1683 };
1684 
1685 const struct coresight_ops tmc_etr_cs_ops = {
1686 	.sink_ops	= &tmc_etr_sink_ops,
1687 };
1688 
1689 int tmc_read_prepare_etr(struct tmc_drvdata *drvdata)
1690 {
1691 	int ret = 0;
1692 	unsigned long flags;
1693 
1694 	/* config types are set a boot time and never change */
1695 	if (WARN_ON_ONCE(drvdata->config_type != TMC_CONFIG_TYPE_ETR))
1696 		return -EINVAL;
1697 
1698 	spin_lock_irqsave(&drvdata->spinlock, flags);
1699 	if (drvdata->reading) {
1700 		ret = -EBUSY;
1701 		goto out;
1702 	}
1703 
1704 	/*
1705 	 * We can safely allow reads even if the ETR is operating in PERF mode,
1706 	 * since the sysfs session is captured in mode specific data.
1707 	 * If drvdata::sysfs_data is NULL the trace data has been read already.
1708 	 */
1709 	if (!drvdata->sysfs_buf) {
1710 		ret = -EINVAL;
1711 		goto out;
1712 	}
1713 
1714 	/* Disable the TMC if we are trying to read from a running session. */
1715 	if (drvdata->mode == CS_MODE_SYSFS)
1716 		__tmc_etr_disable_hw(drvdata);
1717 
1718 	drvdata->reading = true;
1719 out:
1720 	spin_unlock_irqrestore(&drvdata->spinlock, flags);
1721 
1722 	return ret;
1723 }
1724 
1725 int tmc_read_unprepare_etr(struct tmc_drvdata *drvdata)
1726 {
1727 	unsigned long flags;
1728 	struct etr_buf *sysfs_buf = NULL;
1729 
1730 	/* config types are set a boot time and never change */
1731 	if (WARN_ON_ONCE(drvdata->config_type != TMC_CONFIG_TYPE_ETR))
1732 		return -EINVAL;
1733 
1734 	spin_lock_irqsave(&drvdata->spinlock, flags);
1735 
1736 	/* RE-enable the TMC if need be */
1737 	if (drvdata->mode == CS_MODE_SYSFS) {
1738 		/*
1739 		 * The trace run will continue with the same allocated trace
1740 		 * buffer. Since the tracer is still enabled drvdata::buf can't
1741 		 * be NULL.
1742 		 */
1743 		__tmc_etr_enable_hw(drvdata);
1744 	} else {
1745 		/*
1746 		 * The ETR is not tracing and the buffer was just read.
1747 		 * As such prepare to free the trace buffer.
1748 		 */
1749 		sysfs_buf = drvdata->sysfs_buf;
1750 		drvdata->sysfs_buf = NULL;
1751 	}
1752 
1753 	drvdata->reading = false;
1754 	spin_unlock_irqrestore(&drvdata->spinlock, flags);
1755 
1756 	/* Free allocated memory out side of the spinlock */
1757 	if (sysfs_buf)
1758 		tmc_etr_free_sysfs_buf(sysfs_buf);
1759 
1760 	return 0;
1761 }
1762