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