xref: /linux/drivers/gpu/drm/xe/xe_oa.c (revision 37aeccf5f839c155e8c9100937a01059b24e61b5)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2023-2024 Intel Corporation
4  */
5 
6 #include <linux/anon_inodes.h>
7 #include <linux/delay.h>
8 #include <linux/nospec.h>
9 #include <linux/poll.h>
10 
11 #include <drm/drm_drv.h>
12 #include <drm/drm_managed.h>
13 #include <uapi/drm/xe_drm.h>
14 
15 #include "abi/guc_actions_slpc_abi.h"
16 #include "instructions/xe_mi_commands.h"
17 #include "regs/xe_engine_regs.h"
18 #include "regs/xe_gt_regs.h"
19 #include "regs/xe_lrc_layout.h"
20 #include "regs/xe_oa_regs.h"
21 #include "xe_assert.h"
22 #include "xe_bb.h"
23 #include "xe_bo.h"
24 #include "xe_device.h"
25 #include "xe_exec_queue.h"
26 #include "xe_force_wake.h"
27 #include "xe_gt.h"
28 #include "xe_gt_mcr.h"
29 #include "xe_gt_printk.h"
30 #include "xe_guc_pc.h"
31 #include "xe_lrc.h"
32 #include "xe_macros.h"
33 #include "xe_mmio.h"
34 #include "xe_oa.h"
35 #include "xe_observation.h"
36 #include "xe_pm.h"
37 #include "xe_sched_job.h"
38 #include "xe_sriov.h"
39 
40 #define DEFAULT_POLL_FREQUENCY_HZ 200
41 #define DEFAULT_POLL_PERIOD_NS (NSEC_PER_SEC / DEFAULT_POLL_FREQUENCY_HZ)
42 #define XE_OA_UNIT_INVALID U32_MAX
43 
44 struct xe_oa_reg {
45 	struct xe_reg addr;
46 	u32 value;
47 };
48 
49 struct xe_oa_config {
50 	struct xe_oa *oa;
51 
52 	char uuid[UUID_STRING_LEN + 1];
53 	int id;
54 
55 	const struct xe_oa_reg *regs;
56 	u32 regs_len;
57 
58 	struct attribute_group sysfs_metric;
59 	struct attribute *attrs[2];
60 	struct kobj_attribute sysfs_metric_id;
61 
62 	struct kref ref;
63 	struct rcu_head rcu;
64 };
65 
66 struct flex {
67 	struct xe_reg reg;
68 	u32 offset;
69 	u32 value;
70 };
71 
72 struct xe_oa_open_param {
73 	u32 oa_unit_id;
74 	bool sample;
75 	u32 metric_set;
76 	enum xe_oa_format_name oa_format;
77 	int period_exponent;
78 	bool disabled;
79 	int exec_queue_id;
80 	int engine_instance;
81 	struct xe_exec_queue *exec_q;
82 	struct xe_hw_engine *hwe;
83 	bool no_preempt;
84 };
85 
86 struct xe_oa_config_bo {
87 	struct llist_node node;
88 
89 	struct xe_oa_config *oa_config;
90 	struct xe_bb *bb;
91 };
92 
93 #define DRM_FMT(x) DRM_XE_OA_FMT_TYPE_##x
94 
95 static const struct xe_oa_format oa_formats[] = {
96 	[XE_OA_FORMAT_C4_B8]			= { 7, 64,  DRM_FMT(OAG) },
97 	[XE_OA_FORMAT_A12]			= { 0, 64,  DRM_FMT(OAG) },
98 	[XE_OA_FORMAT_A12_B8_C8]		= { 2, 128, DRM_FMT(OAG) },
99 	[XE_OA_FORMAT_A32u40_A4u32_B8_C8]	= { 5, 256, DRM_FMT(OAG) },
100 	[XE_OAR_FORMAT_A32u40_A4u32_B8_C8]	= { 5, 256, DRM_FMT(OAR) },
101 	[XE_OA_FORMAT_A24u40_A14u32_B8_C8]	= { 5, 256, DRM_FMT(OAG) },
102 	[XE_OAC_FORMAT_A24u64_B8_C8]		= { 1, 320, DRM_FMT(OAC), HDR_64_BIT },
103 	[XE_OAC_FORMAT_A22u32_R2u32_B8_C8]	= { 2, 192, DRM_FMT(OAC), HDR_64_BIT },
104 	[XE_OAM_FORMAT_MPEC8u64_B8_C8]		= { 1, 192, DRM_FMT(OAM_MPEC), HDR_64_BIT },
105 	[XE_OAM_FORMAT_MPEC8u32_B8_C8]		= { 2, 128, DRM_FMT(OAM_MPEC), HDR_64_BIT },
106 	[XE_OA_FORMAT_PEC64u64]			= { 1, 576, DRM_FMT(PEC), HDR_64_BIT, 1, 0 },
107 	[XE_OA_FORMAT_PEC64u64_B8_C8]		= { 1, 640, DRM_FMT(PEC), HDR_64_BIT, 1, 1 },
108 	[XE_OA_FORMAT_PEC64u32]			= { 1, 320, DRM_FMT(PEC), HDR_64_BIT },
109 	[XE_OA_FORMAT_PEC32u64_G1]		= { 5, 320, DRM_FMT(PEC), HDR_64_BIT, 1, 0 },
110 	[XE_OA_FORMAT_PEC32u32_G1]		= { 5, 192, DRM_FMT(PEC), HDR_64_BIT },
111 	[XE_OA_FORMAT_PEC32u64_G2]		= { 6, 320, DRM_FMT(PEC), HDR_64_BIT, 1, 0 },
112 	[XE_OA_FORMAT_PEC32u32_G2]		= { 6, 192, DRM_FMT(PEC), HDR_64_BIT },
113 	[XE_OA_FORMAT_PEC36u64_G1_32_G2_4]	= { 3, 320, DRM_FMT(PEC), HDR_64_BIT, 1, 0 },
114 	[XE_OA_FORMAT_PEC36u64_G1_4_G2_32]	= { 4, 320, DRM_FMT(PEC), HDR_64_BIT, 1, 0 },
115 };
116 
117 static u32 xe_oa_circ_diff(struct xe_oa_stream *stream, u32 tail, u32 head)
118 {
119 	return tail >= head ? tail - head :
120 		tail + stream->oa_buffer.circ_size - head;
121 }
122 
123 static u32 xe_oa_circ_incr(struct xe_oa_stream *stream, u32 ptr, u32 n)
124 {
125 	return ptr + n >= stream->oa_buffer.circ_size ?
126 		ptr + n - stream->oa_buffer.circ_size : ptr + n;
127 }
128 
129 static void xe_oa_config_release(struct kref *ref)
130 {
131 	struct xe_oa_config *oa_config =
132 		container_of(ref, typeof(*oa_config), ref);
133 
134 	kfree(oa_config->regs);
135 
136 	kfree_rcu(oa_config, rcu);
137 }
138 
139 static void xe_oa_config_put(struct xe_oa_config *oa_config)
140 {
141 	if (!oa_config)
142 		return;
143 
144 	kref_put(&oa_config->ref, xe_oa_config_release);
145 }
146 
147 static struct xe_oa_config *xe_oa_config_get(struct xe_oa_config *oa_config)
148 {
149 	return kref_get_unless_zero(&oa_config->ref) ? oa_config : NULL;
150 }
151 
152 static struct xe_oa_config *xe_oa_get_oa_config(struct xe_oa *oa, int metrics_set)
153 {
154 	struct xe_oa_config *oa_config;
155 
156 	rcu_read_lock();
157 	oa_config = idr_find(&oa->metrics_idr, metrics_set);
158 	if (oa_config)
159 		oa_config = xe_oa_config_get(oa_config);
160 	rcu_read_unlock();
161 
162 	return oa_config;
163 }
164 
165 static void free_oa_config_bo(struct xe_oa_config_bo *oa_bo)
166 {
167 	xe_oa_config_put(oa_bo->oa_config);
168 	xe_bb_free(oa_bo->bb, NULL);
169 	kfree(oa_bo);
170 }
171 
172 static const struct xe_oa_regs *__oa_regs(struct xe_oa_stream *stream)
173 {
174 	return &stream->hwe->oa_unit->regs;
175 }
176 
177 static u32 xe_oa_hw_tail_read(struct xe_oa_stream *stream)
178 {
179 	return xe_mmio_read32(&stream->gt->mmio, __oa_regs(stream)->oa_tail_ptr) &
180 		OAG_OATAILPTR_MASK;
181 }
182 
183 #define oa_report_header_64bit(__s) \
184 	((__s)->oa_buffer.format->header == HDR_64_BIT)
185 
186 static u64 oa_report_id(struct xe_oa_stream *stream, void *report)
187 {
188 	return oa_report_header_64bit(stream) ? *(u64 *)report : *(u32 *)report;
189 }
190 
191 static void oa_report_id_clear(struct xe_oa_stream *stream, u32 *report)
192 {
193 	if (oa_report_header_64bit(stream))
194 		*(u64 *)report = 0;
195 	else
196 		*report = 0;
197 }
198 
199 static u64 oa_timestamp(struct xe_oa_stream *stream, void *report)
200 {
201 	return oa_report_header_64bit(stream) ?
202 		*((u64 *)report + 1) :
203 		*((u32 *)report + 1);
204 }
205 
206 static void oa_timestamp_clear(struct xe_oa_stream *stream, u32 *report)
207 {
208 	if (oa_report_header_64bit(stream))
209 		*(u64 *)&report[2] = 0;
210 	else
211 		report[1] = 0;
212 }
213 
214 static bool xe_oa_buffer_check_unlocked(struct xe_oa_stream *stream)
215 {
216 	u32 gtt_offset = xe_bo_ggtt_addr(stream->oa_buffer.bo);
217 	int report_size = stream->oa_buffer.format->size;
218 	u32 tail, hw_tail;
219 	unsigned long flags;
220 	bool pollin;
221 	u32 partial_report_size;
222 
223 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
224 
225 	hw_tail = xe_oa_hw_tail_read(stream);
226 	hw_tail -= gtt_offset;
227 
228 	/*
229 	 * The tail pointer increases in 64 byte (cacheline size), not in report_size
230 	 * increments. Also report size may not be a power of 2. Compute potential
231 	 * partially landed report in OA buffer.
232 	 */
233 	partial_report_size = xe_oa_circ_diff(stream, hw_tail, stream->oa_buffer.tail);
234 	partial_report_size %= report_size;
235 
236 	/* Subtract partial amount off the tail */
237 	hw_tail = xe_oa_circ_diff(stream, hw_tail, partial_report_size);
238 
239 	tail = hw_tail;
240 
241 	/*
242 	 * Walk the stream backward until we find a report with report id and timestamp
243 	 * not 0. We can't tell whether a report has fully landed in memory before the
244 	 * report id and timestamp of the following report have landed.
245 	 *
246 	 * This is assuming that the writes of the OA unit land in memory in the order
247 	 * they were written.  If not : (╯°□°)╯︵ ┻━┻
248 	 */
249 	while (xe_oa_circ_diff(stream, tail, stream->oa_buffer.tail) >= report_size) {
250 		void *report = stream->oa_buffer.vaddr + tail;
251 
252 		if (oa_report_id(stream, report) || oa_timestamp(stream, report))
253 			break;
254 
255 		tail = xe_oa_circ_diff(stream, tail, report_size);
256 	}
257 
258 	if (xe_oa_circ_diff(stream, hw_tail, tail) > report_size)
259 		drm_dbg(&stream->oa->xe->drm,
260 			"unlanded report(s) head=0x%x tail=0x%x hw_tail=0x%x\n",
261 			stream->oa_buffer.head, tail, hw_tail);
262 
263 	stream->oa_buffer.tail = tail;
264 
265 	pollin = xe_oa_circ_diff(stream, stream->oa_buffer.tail,
266 				 stream->oa_buffer.head) >= report_size;
267 
268 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
269 
270 	return pollin;
271 }
272 
273 static enum hrtimer_restart xe_oa_poll_check_timer_cb(struct hrtimer *hrtimer)
274 {
275 	struct xe_oa_stream *stream =
276 		container_of(hrtimer, typeof(*stream), poll_check_timer);
277 
278 	if (xe_oa_buffer_check_unlocked(stream)) {
279 		stream->pollin = true;
280 		wake_up(&stream->poll_wq);
281 	}
282 
283 	hrtimer_forward_now(hrtimer, ns_to_ktime(stream->poll_period_ns));
284 
285 	return HRTIMER_RESTART;
286 }
287 
288 static int xe_oa_append_report(struct xe_oa_stream *stream, char __user *buf,
289 			       size_t count, size_t *offset, const u8 *report)
290 {
291 	int report_size = stream->oa_buffer.format->size;
292 	int report_size_partial;
293 	u8 *oa_buf_end;
294 
295 	if ((count - *offset) < report_size)
296 		return -ENOSPC;
297 
298 	buf += *offset;
299 
300 	oa_buf_end = stream->oa_buffer.vaddr + stream->oa_buffer.circ_size;
301 	report_size_partial = oa_buf_end - report;
302 
303 	if (report_size_partial < report_size) {
304 		if (copy_to_user(buf, report, report_size_partial))
305 			return -EFAULT;
306 		buf += report_size_partial;
307 
308 		if (copy_to_user(buf, stream->oa_buffer.vaddr,
309 				 report_size - report_size_partial))
310 			return -EFAULT;
311 	} else if (copy_to_user(buf, report, report_size)) {
312 		return -EFAULT;
313 	}
314 
315 	*offset += report_size;
316 
317 	return 0;
318 }
319 
320 static int xe_oa_append_reports(struct xe_oa_stream *stream, char __user *buf,
321 				size_t count, size_t *offset)
322 {
323 	int report_size = stream->oa_buffer.format->size;
324 	u8 *oa_buf_base = stream->oa_buffer.vaddr;
325 	u32 gtt_offset = xe_bo_ggtt_addr(stream->oa_buffer.bo);
326 	size_t start_offset = *offset;
327 	unsigned long flags;
328 	u32 head, tail;
329 	int ret = 0;
330 
331 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
332 	head = stream->oa_buffer.head;
333 	tail = stream->oa_buffer.tail;
334 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
335 
336 	xe_assert(stream->oa->xe,
337 		  head < stream->oa_buffer.circ_size && tail < stream->oa_buffer.circ_size);
338 
339 	for (; xe_oa_circ_diff(stream, tail, head);
340 	     head = xe_oa_circ_incr(stream, head, report_size)) {
341 		u8 *report = oa_buf_base + head;
342 
343 		ret = xe_oa_append_report(stream, buf, count, offset, report);
344 		if (ret)
345 			break;
346 
347 		if (!(stream->oa_buffer.circ_size % report_size)) {
348 			/* Clear out report id and timestamp to detect unlanded reports */
349 			oa_report_id_clear(stream, (void *)report);
350 			oa_timestamp_clear(stream, (void *)report);
351 		} else {
352 			u8 *oa_buf_end = stream->oa_buffer.vaddr + stream->oa_buffer.circ_size;
353 			u32 part = oa_buf_end - report;
354 
355 			/* Zero out the entire report */
356 			if (report_size <= part) {
357 				memset(report, 0, report_size);
358 			} else {
359 				memset(report, 0, part);
360 				memset(oa_buf_base, 0, report_size - part);
361 			}
362 		}
363 	}
364 
365 	if (start_offset != *offset) {
366 		struct xe_reg oaheadptr = __oa_regs(stream)->oa_head_ptr;
367 
368 		spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
369 		xe_mmio_write32(&stream->gt->mmio, oaheadptr,
370 				(head + gtt_offset) & OAG_OAHEADPTR_MASK);
371 		stream->oa_buffer.head = head;
372 		spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
373 	}
374 
375 	return ret;
376 }
377 
378 static void xe_oa_init_oa_buffer(struct xe_oa_stream *stream)
379 {
380 	struct xe_mmio *mmio = &stream->gt->mmio;
381 	u32 gtt_offset = xe_bo_ggtt_addr(stream->oa_buffer.bo);
382 	u32 oa_buf = gtt_offset | OABUFFER_SIZE_16M | OAG_OABUFFER_MEMORY_SELECT;
383 	unsigned long flags;
384 
385 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
386 
387 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_status, 0);
388 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_head_ptr,
389 			gtt_offset & OAG_OAHEADPTR_MASK);
390 	stream->oa_buffer.head = 0;
391 	/*
392 	 * PRM says: "This MMIO must be set before the OATAILPTR register and after the
393 	 * OAHEADPTR register. This is to enable proper functionality of the overflow bit".
394 	 */
395 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_buffer, oa_buf);
396 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_tail_ptr,
397 			gtt_offset & OAG_OATAILPTR_MASK);
398 
399 	/* Mark that we need updated tail pointer to read from */
400 	stream->oa_buffer.tail = 0;
401 
402 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
403 
404 	/* Zero out the OA buffer since we rely on zero report id and timestamp fields */
405 	memset(stream->oa_buffer.vaddr, 0, stream->oa_buffer.bo->size);
406 }
407 
408 static u32 __format_to_oactrl(const struct xe_oa_format *format, int counter_sel_mask)
409 {
410 	return ((format->counter_select << (ffs(counter_sel_mask) - 1)) & counter_sel_mask) |
411 		REG_FIELD_PREP(OA_OACONTROL_REPORT_BC_MASK, format->bc_report) |
412 		REG_FIELD_PREP(OA_OACONTROL_COUNTER_SIZE_MASK, format->counter_size);
413 }
414 
415 static u32 __oa_ccs_select(struct xe_oa_stream *stream)
416 {
417 	u32 val;
418 
419 	if (stream->hwe->class != XE_ENGINE_CLASS_COMPUTE)
420 		return 0;
421 
422 	val = REG_FIELD_PREP(OAG_OACONTROL_OA_CCS_SELECT_MASK, stream->hwe->instance);
423 	xe_assert(stream->oa->xe,
424 		  REG_FIELD_GET(OAG_OACONTROL_OA_CCS_SELECT_MASK, val) == stream->hwe->instance);
425 	return val;
426 }
427 
428 static void xe_oa_enable(struct xe_oa_stream *stream)
429 {
430 	const struct xe_oa_format *format = stream->oa_buffer.format;
431 	const struct xe_oa_regs *regs;
432 	u32 val;
433 
434 	/*
435 	 * BSpec: 46822: Bit 0. Even if stream->sample is 0, for OAR to function, the OA
436 	 * buffer must be correctly initialized
437 	 */
438 	xe_oa_init_oa_buffer(stream);
439 
440 	regs = __oa_regs(stream);
441 	val = __format_to_oactrl(format, regs->oa_ctrl_counter_select_mask) |
442 		__oa_ccs_select(stream) | OAG_OACONTROL_OA_COUNTER_ENABLE;
443 
444 	if (GRAPHICS_VER(stream->oa->xe) >= 20 &&
445 	    stream->hwe->oa_unit->type == DRM_XE_OA_UNIT_TYPE_OAG)
446 		val |= OAG_OACONTROL_OA_PES_DISAG_EN;
447 
448 	xe_mmio_write32(&stream->gt->mmio, regs->oa_ctrl, val);
449 }
450 
451 static void xe_oa_disable(struct xe_oa_stream *stream)
452 {
453 	struct xe_mmio *mmio = &stream->gt->mmio;
454 
455 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_ctrl, 0);
456 	if (xe_mmio_wait32(mmio, __oa_regs(stream)->oa_ctrl,
457 			   OAG_OACONTROL_OA_COUNTER_ENABLE, 0, 50000, NULL, false))
458 		drm_err(&stream->oa->xe->drm,
459 			"wait for OA to be disabled timed out\n");
460 
461 	if (GRAPHICS_VERx100(stream->oa->xe) <= 1270 && GRAPHICS_VERx100(stream->oa->xe) != 1260) {
462 		/* <= XE_METEORLAKE except XE_PVC */
463 		xe_mmio_write32(mmio, OA_TLB_INV_CR, 1);
464 		if (xe_mmio_wait32(mmio, OA_TLB_INV_CR, 1, 0, 50000, NULL, false))
465 			drm_err(&stream->oa->xe->drm,
466 				"wait for OA tlb invalidate timed out\n");
467 	}
468 }
469 
470 static int xe_oa_wait_unlocked(struct xe_oa_stream *stream)
471 {
472 	/* We might wait indefinitely if periodic sampling is not enabled */
473 	if (!stream->periodic)
474 		return -EINVAL;
475 
476 	return wait_event_interruptible(stream->poll_wq,
477 					xe_oa_buffer_check_unlocked(stream));
478 }
479 
480 #define OASTATUS_RELEVANT_BITS (OASTATUS_MMIO_TRG_Q_FULL | OASTATUS_COUNTER_OVERFLOW | \
481 				OASTATUS_BUFFER_OVERFLOW | OASTATUS_REPORT_LOST)
482 
483 static int __xe_oa_read(struct xe_oa_stream *stream, char __user *buf,
484 			size_t count, size_t *offset)
485 {
486 	/* Only clear our bits to avoid side-effects */
487 	stream->oa_status = xe_mmio_rmw32(&stream->gt->mmio, __oa_regs(stream)->oa_status,
488 					  OASTATUS_RELEVANT_BITS, 0);
489 	/*
490 	 * Signal to userspace that there is non-zero OA status to read via
491 	 * @DRM_XE_OBSERVATION_IOCTL_STATUS observation stream fd ioctl
492 	 */
493 	if (stream->oa_status & OASTATUS_RELEVANT_BITS)
494 		return -EIO;
495 
496 	return xe_oa_append_reports(stream, buf, count, offset);
497 }
498 
499 static ssize_t xe_oa_read(struct file *file, char __user *buf,
500 			  size_t count, loff_t *ppos)
501 {
502 	struct xe_oa_stream *stream = file->private_data;
503 	size_t offset = 0;
504 	int ret;
505 
506 	/* Can't read from disabled streams */
507 	if (!stream->enabled || !stream->sample)
508 		return -EINVAL;
509 
510 	if (!(file->f_flags & O_NONBLOCK)) {
511 		do {
512 			ret = xe_oa_wait_unlocked(stream);
513 			if (ret)
514 				return ret;
515 
516 			mutex_lock(&stream->stream_lock);
517 			ret = __xe_oa_read(stream, buf, count, &offset);
518 			mutex_unlock(&stream->stream_lock);
519 		} while (!offset && !ret);
520 	} else {
521 		mutex_lock(&stream->stream_lock);
522 		ret = __xe_oa_read(stream, buf, count, &offset);
523 		mutex_unlock(&stream->stream_lock);
524 	}
525 
526 	/*
527 	 * Typically we clear pollin here in order to wait for the new hrtimer callback
528 	 * before unblocking. The exception to this is if __xe_oa_read returns -ENOSPC,
529 	 * which means that more OA data is available than could fit in the user provided
530 	 * buffer. In this case we want the next poll() call to not block.
531 	 *
532 	 * Also in case of -EIO, we have already waited for data before returning
533 	 * -EIO, so need to wait again
534 	 */
535 	if (ret != -ENOSPC && ret != -EIO)
536 		stream->pollin = false;
537 
538 	/* Possible values for ret are 0, -EFAULT, -ENOSPC, -EIO, -EINVAL, ... */
539 	return offset ?: (ret ?: -EAGAIN);
540 }
541 
542 static __poll_t xe_oa_poll_locked(struct xe_oa_stream *stream,
543 				  struct file *file, poll_table *wait)
544 {
545 	__poll_t events = 0;
546 
547 	poll_wait(file, &stream->poll_wq, wait);
548 
549 	/*
550 	 * We don't explicitly check whether there's something to read here since this
551 	 * path may be hot depending on what else userspace is polling, or on the timeout
552 	 * in use. We rely on hrtimer xe_oa_poll_check_timer_cb to notify us when there
553 	 * are samples to read
554 	 */
555 	if (stream->pollin)
556 		events |= EPOLLIN;
557 
558 	return events;
559 }
560 
561 static __poll_t xe_oa_poll(struct file *file, poll_table *wait)
562 {
563 	struct xe_oa_stream *stream = file->private_data;
564 	__poll_t ret;
565 
566 	mutex_lock(&stream->stream_lock);
567 	ret = xe_oa_poll_locked(stream, file, wait);
568 	mutex_unlock(&stream->stream_lock);
569 
570 	return ret;
571 }
572 
573 static int xe_oa_submit_bb(struct xe_oa_stream *stream, struct xe_bb *bb)
574 {
575 	struct xe_sched_job *job;
576 	struct dma_fence *fence;
577 	long timeout;
578 	int err = 0;
579 
580 	/* Kernel configuration is issued on stream->k_exec_q, not stream->exec_q */
581 	job = xe_bb_create_job(stream->k_exec_q, bb);
582 	if (IS_ERR(job)) {
583 		err = PTR_ERR(job);
584 		goto exit;
585 	}
586 
587 	xe_sched_job_arm(job);
588 	fence = dma_fence_get(&job->drm.s_fence->finished);
589 	xe_sched_job_push(job);
590 
591 	timeout = dma_fence_wait_timeout(fence, false, HZ);
592 	dma_fence_put(fence);
593 	if (timeout < 0)
594 		err = timeout;
595 	else if (!timeout)
596 		err = -ETIME;
597 exit:
598 	return err;
599 }
600 
601 static void write_cs_mi_lri(struct xe_bb *bb, const struct xe_oa_reg *reg_data, u32 n_regs)
602 {
603 	u32 i;
604 
605 #define MI_LOAD_REGISTER_IMM_MAX_REGS (126)
606 
607 	for (i = 0; i < n_regs; i++) {
608 		if ((i % MI_LOAD_REGISTER_IMM_MAX_REGS) == 0) {
609 			u32 n_lri = min_t(u32, n_regs - i,
610 					  MI_LOAD_REGISTER_IMM_MAX_REGS);
611 
612 			bb->cs[bb->len++] = MI_LOAD_REGISTER_IMM | MI_LRI_NUM_REGS(n_lri);
613 		}
614 		bb->cs[bb->len++] = reg_data[i].addr.addr;
615 		bb->cs[bb->len++] = reg_data[i].value;
616 	}
617 }
618 
619 static int num_lri_dwords(int num_regs)
620 {
621 	int count = 0;
622 
623 	if (num_regs > 0) {
624 		count += DIV_ROUND_UP(num_regs, MI_LOAD_REGISTER_IMM_MAX_REGS);
625 		count += num_regs * 2;
626 	}
627 
628 	return count;
629 }
630 
631 static void xe_oa_free_oa_buffer(struct xe_oa_stream *stream)
632 {
633 	xe_bo_unpin_map_no_vm(stream->oa_buffer.bo);
634 }
635 
636 static void xe_oa_free_configs(struct xe_oa_stream *stream)
637 {
638 	struct xe_oa_config_bo *oa_bo, *tmp;
639 
640 	xe_oa_config_put(stream->oa_config);
641 	llist_for_each_entry_safe(oa_bo, tmp, stream->oa_config_bos.first, node)
642 		free_oa_config_bo(oa_bo);
643 }
644 
645 static void xe_oa_store_flex(struct xe_oa_stream *stream, struct xe_lrc *lrc,
646 			     struct xe_bb *bb, const struct flex *flex, u32 count)
647 {
648 	u32 offset = xe_bo_ggtt_addr(lrc->bo);
649 
650 	do {
651 		bb->cs[bb->len++] = MI_STORE_DATA_IMM | MI_SDI_GGTT | MI_SDI_NUM_DW(1);
652 		bb->cs[bb->len++] = offset + flex->offset * sizeof(u32);
653 		bb->cs[bb->len++] = 0;
654 		bb->cs[bb->len++] = flex->value;
655 
656 	} while (flex++, --count);
657 }
658 
659 static int xe_oa_modify_ctx_image(struct xe_oa_stream *stream, struct xe_lrc *lrc,
660 				  const struct flex *flex, u32 count)
661 {
662 	struct xe_bb *bb;
663 	int err;
664 
665 	bb = xe_bb_new(stream->gt, 4 * count, false);
666 	if (IS_ERR(bb)) {
667 		err = PTR_ERR(bb);
668 		goto exit;
669 	}
670 
671 	xe_oa_store_flex(stream, lrc, bb, flex, count);
672 
673 	err = xe_oa_submit_bb(stream, bb);
674 	xe_bb_free(bb, NULL);
675 exit:
676 	return err;
677 }
678 
679 static int xe_oa_load_with_lri(struct xe_oa_stream *stream, struct xe_oa_reg *reg_lri)
680 {
681 	struct xe_bb *bb;
682 	int err;
683 
684 	bb = xe_bb_new(stream->gt, 3, false);
685 	if (IS_ERR(bb)) {
686 		err = PTR_ERR(bb);
687 		goto exit;
688 	}
689 
690 	write_cs_mi_lri(bb, reg_lri, 1);
691 
692 	err = xe_oa_submit_bb(stream, bb);
693 	xe_bb_free(bb, NULL);
694 exit:
695 	return err;
696 }
697 
698 static int xe_oa_configure_oar_context(struct xe_oa_stream *stream, bool enable)
699 {
700 	const struct xe_oa_format *format = stream->oa_buffer.format;
701 	struct xe_lrc *lrc = stream->exec_q->lrc[0];
702 	u32 regs_offset = xe_lrc_regs_offset(lrc) / sizeof(u32);
703 	u32 oacontrol = __format_to_oactrl(format, OAR_OACONTROL_COUNTER_SEL_MASK) |
704 		(enable ? OAR_OACONTROL_COUNTER_ENABLE : 0);
705 
706 	struct flex regs_context[] = {
707 		{
708 			OACTXCONTROL(stream->hwe->mmio_base),
709 			stream->oa->ctx_oactxctrl_offset[stream->hwe->class] + 1,
710 			enable ? OA_COUNTER_RESUME : 0,
711 		},
712 		{
713 			RING_CONTEXT_CONTROL(stream->hwe->mmio_base),
714 			regs_offset + CTX_CONTEXT_CONTROL,
715 			_MASKED_BIT_ENABLE(CTX_CTRL_OAC_CONTEXT_ENABLE),
716 		},
717 	};
718 	struct xe_oa_reg reg_lri = { OAR_OACONTROL, oacontrol };
719 	int err;
720 
721 	/* Modify stream hwe context image with regs_context */
722 	err = xe_oa_modify_ctx_image(stream, stream->exec_q->lrc[0],
723 				     regs_context, ARRAY_SIZE(regs_context));
724 	if (err)
725 		return err;
726 
727 	/* Apply reg_lri using LRI */
728 	return xe_oa_load_with_lri(stream, &reg_lri);
729 }
730 
731 static int xe_oa_configure_oac_context(struct xe_oa_stream *stream, bool enable)
732 {
733 	const struct xe_oa_format *format = stream->oa_buffer.format;
734 	struct xe_lrc *lrc = stream->exec_q->lrc[0];
735 	u32 regs_offset = xe_lrc_regs_offset(lrc) / sizeof(u32);
736 	u32 oacontrol = __format_to_oactrl(format, OAR_OACONTROL_COUNTER_SEL_MASK) |
737 		(enable ? OAR_OACONTROL_COUNTER_ENABLE : 0);
738 	struct flex regs_context[] = {
739 		{
740 			OACTXCONTROL(stream->hwe->mmio_base),
741 			stream->oa->ctx_oactxctrl_offset[stream->hwe->class] + 1,
742 			enable ? OA_COUNTER_RESUME : 0,
743 		},
744 		{
745 			RING_CONTEXT_CONTROL(stream->hwe->mmio_base),
746 			regs_offset + CTX_CONTEXT_CONTROL,
747 			_MASKED_BIT_ENABLE(CTX_CTRL_OAC_CONTEXT_ENABLE) |
748 			_MASKED_FIELD(CTX_CTRL_RUN_ALONE, enable ? CTX_CTRL_RUN_ALONE : 0),
749 		},
750 	};
751 	struct xe_oa_reg reg_lri = { OAC_OACONTROL, oacontrol };
752 	int err;
753 
754 	/* Set ccs select to enable programming of OAC_OACONTROL */
755 	xe_mmio_write32(&stream->gt->mmio, __oa_regs(stream)->oa_ctrl,
756 			__oa_ccs_select(stream));
757 
758 	/* Modify stream hwe context image with regs_context */
759 	err = xe_oa_modify_ctx_image(stream, stream->exec_q->lrc[0],
760 				     regs_context, ARRAY_SIZE(regs_context));
761 	if (err)
762 		return err;
763 
764 	/* Apply reg_lri using LRI */
765 	return xe_oa_load_with_lri(stream, &reg_lri);
766 }
767 
768 static int xe_oa_configure_oa_context(struct xe_oa_stream *stream, bool enable)
769 {
770 	switch (stream->hwe->class) {
771 	case XE_ENGINE_CLASS_RENDER:
772 		return xe_oa_configure_oar_context(stream, enable);
773 	case XE_ENGINE_CLASS_COMPUTE:
774 		return xe_oa_configure_oac_context(stream, enable);
775 	default:
776 		/* Video engines do not support MI_REPORT_PERF_COUNT */
777 		return 0;
778 	}
779 }
780 
781 #define HAS_OA_BPC_REPORTING(xe) (GRAPHICS_VERx100(xe) >= 1255)
782 
783 static u32 oag_configure_mmio_trigger(const struct xe_oa_stream *stream, bool enable)
784 {
785 	return _MASKED_FIELD(OAG_OA_DEBUG_DISABLE_MMIO_TRG,
786 			     enable && stream && stream->sample ?
787 			     0 : OAG_OA_DEBUG_DISABLE_MMIO_TRG);
788 }
789 
790 static void xe_oa_disable_metric_set(struct xe_oa_stream *stream)
791 {
792 	struct xe_mmio *mmio = &stream->gt->mmio;
793 	u32 sqcnt1;
794 
795 	/*
796 	 * Wa_1508761755:xehpsdv, dg2
797 	 * Enable thread stall DOP gating and EU DOP gating.
798 	 */
799 	if (stream->oa->xe->info.platform == XE_DG2) {
800 		xe_gt_mcr_multicast_write(stream->gt, ROW_CHICKEN,
801 					  _MASKED_BIT_DISABLE(STALL_DOP_GATING_DISABLE));
802 		xe_gt_mcr_multicast_write(stream->gt, ROW_CHICKEN2,
803 					  _MASKED_BIT_DISABLE(DISABLE_DOP_GATING));
804 	}
805 
806 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_debug,
807 			oag_configure_mmio_trigger(stream, false));
808 
809 	/* disable the context save/restore or OAR counters */
810 	if (stream->exec_q)
811 		xe_oa_configure_oa_context(stream, false);
812 
813 	/* Make sure we disable noa to save power. */
814 	xe_mmio_rmw32(mmio, RPM_CONFIG1, GT_NOA_ENABLE, 0);
815 
816 	sqcnt1 = SQCNT1_PMON_ENABLE |
817 		 (HAS_OA_BPC_REPORTING(stream->oa->xe) ? SQCNT1_OABPC : 0);
818 
819 	/* Reset PMON Enable to save power. */
820 	xe_mmio_rmw32(mmio, XELPMP_SQCNT1, sqcnt1, 0);
821 }
822 
823 static void xe_oa_stream_destroy(struct xe_oa_stream *stream)
824 {
825 	struct xe_oa_unit *u = stream->hwe->oa_unit;
826 	struct xe_gt *gt = stream->hwe->gt;
827 
828 	if (WARN_ON(stream != u->exclusive_stream))
829 		return;
830 
831 	WRITE_ONCE(u->exclusive_stream, NULL);
832 
833 	mutex_destroy(&stream->stream_lock);
834 
835 	xe_oa_disable_metric_set(stream);
836 	xe_exec_queue_put(stream->k_exec_q);
837 
838 	xe_oa_free_oa_buffer(stream);
839 
840 	XE_WARN_ON(xe_force_wake_put(gt_to_fw(gt), XE_FORCEWAKE_ALL));
841 	xe_pm_runtime_put(stream->oa->xe);
842 
843 	/* Wa_1509372804:pvc: Unset the override of GUCRC mode to enable rc6 */
844 	if (stream->override_gucrc)
845 		xe_gt_WARN_ON(gt, xe_guc_pc_unset_gucrc_mode(&gt->uc.guc.pc));
846 
847 	xe_oa_free_configs(stream);
848 }
849 
850 static int xe_oa_alloc_oa_buffer(struct xe_oa_stream *stream)
851 {
852 	struct xe_bo *bo;
853 
854 	BUILD_BUG_ON_NOT_POWER_OF_2(XE_OA_BUFFER_SIZE);
855 	BUILD_BUG_ON(XE_OA_BUFFER_SIZE < SZ_128K || XE_OA_BUFFER_SIZE > SZ_16M);
856 
857 	bo = xe_bo_create_pin_map(stream->oa->xe, stream->gt->tile, NULL,
858 				  XE_OA_BUFFER_SIZE, ttm_bo_type_kernel,
859 				  XE_BO_FLAG_SYSTEM | XE_BO_FLAG_GGTT);
860 	if (IS_ERR(bo))
861 		return PTR_ERR(bo);
862 
863 	stream->oa_buffer.bo = bo;
864 	/* mmap implementation requires OA buffer to be in system memory */
865 	xe_assert(stream->oa->xe, bo->vmap.is_iomem == 0);
866 	stream->oa_buffer.vaddr = bo->vmap.vaddr;
867 	return 0;
868 }
869 
870 static struct xe_oa_config_bo *
871 __xe_oa_alloc_config_buffer(struct xe_oa_stream *stream, struct xe_oa_config *oa_config)
872 {
873 	struct xe_oa_config_bo *oa_bo;
874 	size_t config_length;
875 	struct xe_bb *bb;
876 
877 	oa_bo = kzalloc(sizeof(*oa_bo), GFP_KERNEL);
878 	if (!oa_bo)
879 		return ERR_PTR(-ENOMEM);
880 
881 	config_length = num_lri_dwords(oa_config->regs_len);
882 	config_length = ALIGN(sizeof(u32) * config_length, XE_PAGE_SIZE) / sizeof(u32);
883 
884 	bb = xe_bb_new(stream->gt, config_length, false);
885 	if (IS_ERR(bb))
886 		goto err_free;
887 
888 	write_cs_mi_lri(bb, oa_config->regs, oa_config->regs_len);
889 
890 	oa_bo->bb = bb;
891 	oa_bo->oa_config = xe_oa_config_get(oa_config);
892 	llist_add(&oa_bo->node, &stream->oa_config_bos);
893 
894 	return oa_bo;
895 err_free:
896 	kfree(oa_bo);
897 	return ERR_CAST(bb);
898 }
899 
900 static struct xe_oa_config_bo *
901 xe_oa_alloc_config_buffer(struct xe_oa_stream *stream, struct xe_oa_config *oa_config)
902 {
903 	struct xe_oa_config_bo *oa_bo;
904 
905 	/* Look for the buffer in the already allocated BOs attached to the stream */
906 	llist_for_each_entry(oa_bo, stream->oa_config_bos.first, node) {
907 		if (oa_bo->oa_config == oa_config &&
908 		    memcmp(oa_bo->oa_config->uuid, oa_config->uuid,
909 			   sizeof(oa_config->uuid)) == 0)
910 			goto out;
911 	}
912 
913 	oa_bo = __xe_oa_alloc_config_buffer(stream, oa_config);
914 out:
915 	return oa_bo;
916 }
917 
918 static int xe_oa_emit_oa_config(struct xe_oa_stream *stream, struct xe_oa_config *config)
919 {
920 #define NOA_PROGRAM_ADDITIONAL_DELAY_US 500
921 	struct xe_oa_config_bo *oa_bo;
922 	int err, us = NOA_PROGRAM_ADDITIONAL_DELAY_US;
923 
924 	oa_bo = xe_oa_alloc_config_buffer(stream, config);
925 	if (IS_ERR(oa_bo)) {
926 		err = PTR_ERR(oa_bo);
927 		goto exit;
928 	}
929 
930 	err = xe_oa_submit_bb(stream, oa_bo->bb);
931 
932 	/* Additional empirical delay needed for NOA programming after registers are written */
933 	usleep_range(us, 2 * us);
934 exit:
935 	return err;
936 }
937 
938 static u32 oag_report_ctx_switches(const struct xe_oa_stream *stream)
939 {
940 	/* If user didn't require OA reports, ask HW not to emit ctx switch reports */
941 	return _MASKED_FIELD(OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS,
942 			     stream->sample ?
943 			     0 : OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS);
944 }
945 
946 static int xe_oa_enable_metric_set(struct xe_oa_stream *stream)
947 {
948 	struct xe_mmio *mmio = &stream->gt->mmio;
949 	u32 oa_debug, sqcnt1;
950 	int ret;
951 
952 	/*
953 	 * Wa_1508761755:xehpsdv, dg2
954 	 * EU NOA signals behave incorrectly if EU clock gating is enabled.
955 	 * Disable thread stall DOP gating and EU DOP gating.
956 	 */
957 	if (stream->oa->xe->info.platform == XE_DG2) {
958 		xe_gt_mcr_multicast_write(stream->gt, ROW_CHICKEN,
959 					  _MASKED_BIT_ENABLE(STALL_DOP_GATING_DISABLE));
960 		xe_gt_mcr_multicast_write(stream->gt, ROW_CHICKEN2,
961 					  _MASKED_BIT_ENABLE(DISABLE_DOP_GATING));
962 	}
963 
964 	/* Disable clk ratio reports */
965 	oa_debug = OAG_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
966 		OAG_OA_DEBUG_INCLUDE_CLK_RATIO;
967 
968 	if (GRAPHICS_VER(stream->oa->xe) >= 20)
969 		oa_debug |=
970 			/* The three bits below are needed to get PEC counters running */
971 			OAG_OA_DEBUG_START_TRIGGER_SCOPE_CONTROL |
972 			OAG_OA_DEBUG_DISABLE_START_TRG_2_COUNT_QUAL |
973 			OAG_OA_DEBUG_DISABLE_START_TRG_1_COUNT_QUAL;
974 
975 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_debug,
976 			_MASKED_BIT_ENABLE(oa_debug) |
977 			oag_report_ctx_switches(stream) |
978 			oag_configure_mmio_trigger(stream, true));
979 
980 	xe_mmio_write32(mmio, __oa_regs(stream)->oa_ctx_ctrl, stream->periodic ?
981 			(OAG_OAGLBCTXCTRL_COUNTER_RESUME |
982 			 OAG_OAGLBCTXCTRL_TIMER_ENABLE |
983 			 REG_FIELD_PREP(OAG_OAGLBCTXCTRL_TIMER_PERIOD_MASK,
984 					stream->period_exponent)) : 0);
985 
986 	/*
987 	 * Initialize Super Queue Internal Cnt Register
988 	 * Set PMON Enable in order to collect valid metrics
989 	 * Enable bytes per clock reporting
990 	 */
991 	sqcnt1 = SQCNT1_PMON_ENABLE |
992 		 (HAS_OA_BPC_REPORTING(stream->oa->xe) ? SQCNT1_OABPC : 0);
993 
994 	xe_mmio_rmw32(mmio, XELPMP_SQCNT1, 0, sqcnt1);
995 
996 	/* Configure OAR/OAC */
997 	if (stream->exec_q) {
998 		ret = xe_oa_configure_oa_context(stream, true);
999 		if (ret)
1000 			return ret;
1001 	}
1002 
1003 	return xe_oa_emit_oa_config(stream, stream->oa_config);
1004 }
1005 
1006 static void xe_oa_stream_enable(struct xe_oa_stream *stream)
1007 {
1008 	stream->pollin = false;
1009 
1010 	xe_oa_enable(stream);
1011 
1012 	if (stream->sample)
1013 		hrtimer_start(&stream->poll_check_timer,
1014 			      ns_to_ktime(stream->poll_period_ns),
1015 			      HRTIMER_MODE_REL_PINNED);
1016 }
1017 
1018 static void xe_oa_stream_disable(struct xe_oa_stream *stream)
1019 {
1020 	xe_oa_disable(stream);
1021 
1022 	if (stream->sample)
1023 		hrtimer_cancel(&stream->poll_check_timer);
1024 }
1025 
1026 static int xe_oa_enable_preempt_timeslice(struct xe_oa_stream *stream)
1027 {
1028 	struct xe_exec_queue *q = stream->exec_q;
1029 	int ret1, ret2;
1030 
1031 	/* Best effort recovery: try to revert both to original, irrespective of error */
1032 	ret1 = q->ops->set_timeslice(q, stream->hwe->eclass->sched_props.timeslice_us);
1033 	ret2 = q->ops->set_preempt_timeout(q, stream->hwe->eclass->sched_props.preempt_timeout_us);
1034 	if (ret1 || ret2)
1035 		goto err;
1036 	return 0;
1037 err:
1038 	drm_dbg(&stream->oa->xe->drm, "%s failed ret1 %d ret2 %d\n", __func__, ret1, ret2);
1039 	return ret1 ?: ret2;
1040 }
1041 
1042 static int xe_oa_disable_preempt_timeslice(struct xe_oa_stream *stream)
1043 {
1044 	struct xe_exec_queue *q = stream->exec_q;
1045 	int ret;
1046 
1047 	/* Setting values to 0 will disable timeslice and preempt_timeout */
1048 	ret = q->ops->set_timeslice(q, 0);
1049 	if (ret)
1050 		goto err;
1051 
1052 	ret = q->ops->set_preempt_timeout(q, 0);
1053 	if (ret)
1054 		goto err;
1055 
1056 	return 0;
1057 err:
1058 	xe_oa_enable_preempt_timeslice(stream);
1059 	drm_dbg(&stream->oa->xe->drm, "%s failed %d\n", __func__, ret);
1060 	return ret;
1061 }
1062 
1063 static int xe_oa_enable_locked(struct xe_oa_stream *stream)
1064 {
1065 	if (stream->enabled)
1066 		return 0;
1067 
1068 	if (stream->no_preempt) {
1069 		int ret = xe_oa_disable_preempt_timeslice(stream);
1070 
1071 		if (ret)
1072 			return ret;
1073 	}
1074 
1075 	xe_oa_stream_enable(stream);
1076 
1077 	stream->enabled = true;
1078 	return 0;
1079 }
1080 
1081 static int xe_oa_disable_locked(struct xe_oa_stream *stream)
1082 {
1083 	int ret = 0;
1084 
1085 	if (!stream->enabled)
1086 		return 0;
1087 
1088 	xe_oa_stream_disable(stream);
1089 
1090 	if (stream->no_preempt)
1091 		ret = xe_oa_enable_preempt_timeslice(stream);
1092 
1093 	stream->enabled = false;
1094 	return ret;
1095 }
1096 
1097 static long xe_oa_config_locked(struct xe_oa_stream *stream, u64 arg)
1098 {
1099 	struct drm_xe_ext_set_property ext;
1100 	long ret = stream->oa_config->id;
1101 	struct xe_oa_config *config;
1102 	int err;
1103 
1104 	err = __copy_from_user(&ext, u64_to_user_ptr(arg), sizeof(ext));
1105 	if (XE_IOCTL_DBG(stream->oa->xe, err))
1106 		return -EFAULT;
1107 
1108 	if (XE_IOCTL_DBG(stream->oa->xe, ext.pad) ||
1109 	    XE_IOCTL_DBG(stream->oa->xe, ext.base.name != DRM_XE_OA_EXTENSION_SET_PROPERTY) ||
1110 	    XE_IOCTL_DBG(stream->oa->xe, ext.base.next_extension) ||
1111 	    XE_IOCTL_DBG(stream->oa->xe, ext.property != DRM_XE_OA_PROPERTY_OA_METRIC_SET))
1112 		return -EINVAL;
1113 
1114 	config = xe_oa_get_oa_config(stream->oa, ext.value);
1115 	if (!config)
1116 		return -ENODEV;
1117 
1118 	if (config != stream->oa_config) {
1119 		err = xe_oa_emit_oa_config(stream, config);
1120 		if (!err)
1121 			config = xchg(&stream->oa_config, config);
1122 		else
1123 			ret = err;
1124 	}
1125 
1126 	xe_oa_config_put(config);
1127 
1128 	return ret;
1129 }
1130 
1131 static long xe_oa_status_locked(struct xe_oa_stream *stream, unsigned long arg)
1132 {
1133 	struct drm_xe_oa_stream_status status = {};
1134 	void __user *uaddr = (void __user *)arg;
1135 
1136 	/* Map from register to uapi bits */
1137 	if (stream->oa_status & OASTATUS_REPORT_LOST)
1138 		status.oa_status |= DRM_XE_OASTATUS_REPORT_LOST;
1139 	if (stream->oa_status & OASTATUS_BUFFER_OVERFLOW)
1140 		status.oa_status |= DRM_XE_OASTATUS_BUFFER_OVERFLOW;
1141 	if (stream->oa_status & OASTATUS_COUNTER_OVERFLOW)
1142 		status.oa_status |= DRM_XE_OASTATUS_COUNTER_OVERFLOW;
1143 	if (stream->oa_status & OASTATUS_MMIO_TRG_Q_FULL)
1144 		status.oa_status |= DRM_XE_OASTATUS_MMIO_TRG_Q_FULL;
1145 
1146 	if (copy_to_user(uaddr, &status, sizeof(status)))
1147 		return -EFAULT;
1148 
1149 	return 0;
1150 }
1151 
1152 static long xe_oa_info_locked(struct xe_oa_stream *stream, unsigned long arg)
1153 {
1154 	struct drm_xe_oa_stream_info info = { .oa_buf_size = XE_OA_BUFFER_SIZE, };
1155 	void __user *uaddr = (void __user *)arg;
1156 
1157 	if (copy_to_user(uaddr, &info, sizeof(info)))
1158 		return -EFAULT;
1159 
1160 	return 0;
1161 }
1162 
1163 static long xe_oa_ioctl_locked(struct xe_oa_stream *stream,
1164 			       unsigned int cmd,
1165 			       unsigned long arg)
1166 {
1167 	switch (cmd) {
1168 	case DRM_XE_OBSERVATION_IOCTL_ENABLE:
1169 		return xe_oa_enable_locked(stream);
1170 	case DRM_XE_OBSERVATION_IOCTL_DISABLE:
1171 		return xe_oa_disable_locked(stream);
1172 	case DRM_XE_OBSERVATION_IOCTL_CONFIG:
1173 		return xe_oa_config_locked(stream, arg);
1174 	case DRM_XE_OBSERVATION_IOCTL_STATUS:
1175 		return xe_oa_status_locked(stream, arg);
1176 	case DRM_XE_OBSERVATION_IOCTL_INFO:
1177 		return xe_oa_info_locked(stream, arg);
1178 	}
1179 
1180 	return -EINVAL;
1181 }
1182 
1183 static long xe_oa_ioctl(struct file *file,
1184 			unsigned int cmd,
1185 			unsigned long arg)
1186 {
1187 	struct xe_oa_stream *stream = file->private_data;
1188 	long ret;
1189 
1190 	mutex_lock(&stream->stream_lock);
1191 	ret = xe_oa_ioctl_locked(stream, cmd, arg);
1192 	mutex_unlock(&stream->stream_lock);
1193 
1194 	return ret;
1195 }
1196 
1197 static void xe_oa_destroy_locked(struct xe_oa_stream *stream)
1198 {
1199 	if (stream->enabled)
1200 		xe_oa_disable_locked(stream);
1201 
1202 	xe_oa_stream_destroy(stream);
1203 
1204 	if (stream->exec_q)
1205 		xe_exec_queue_put(stream->exec_q);
1206 
1207 	kfree(stream);
1208 }
1209 
1210 static int xe_oa_release(struct inode *inode, struct file *file)
1211 {
1212 	struct xe_oa_stream *stream = file->private_data;
1213 	struct xe_gt *gt = stream->gt;
1214 
1215 	mutex_lock(&gt->oa.gt_lock);
1216 	xe_oa_destroy_locked(stream);
1217 	mutex_unlock(&gt->oa.gt_lock);
1218 
1219 	/* Release the reference the OA stream kept on the driver */
1220 	drm_dev_put(&gt_to_xe(gt)->drm);
1221 
1222 	return 0;
1223 }
1224 
1225 static int xe_oa_mmap(struct file *file, struct vm_area_struct *vma)
1226 {
1227 	struct xe_oa_stream *stream = file->private_data;
1228 	struct xe_bo *bo = stream->oa_buffer.bo;
1229 	unsigned long start = vma->vm_start;
1230 	int i, ret;
1231 
1232 	if (xe_observation_paranoid && !perfmon_capable()) {
1233 		drm_dbg(&stream->oa->xe->drm, "Insufficient privilege to map OA buffer\n");
1234 		return -EACCES;
1235 	}
1236 
1237 	/* Can mmap the entire OA buffer or nothing (no partial OA buffer mmaps) */
1238 	if (vma->vm_end - vma->vm_start != XE_OA_BUFFER_SIZE) {
1239 		drm_dbg(&stream->oa->xe->drm, "Wrong mmap size, must be OA buffer size\n");
1240 		return -EINVAL;
1241 	}
1242 
1243 	/*
1244 	 * Only support VM_READ, enforce MAP_PRIVATE by checking for
1245 	 * VM_MAYSHARE, don't copy the vma on fork
1246 	 */
1247 	if (vma->vm_flags & (VM_WRITE | VM_EXEC | VM_SHARED | VM_MAYSHARE)) {
1248 		drm_dbg(&stream->oa->xe->drm, "mmap must be read only\n");
1249 		return -EINVAL;
1250 	}
1251 	vm_flags_mod(vma, VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP | VM_DONTCOPY,
1252 		     VM_MAYWRITE | VM_MAYEXEC);
1253 
1254 	xe_assert(stream->oa->xe, bo->ttm.ttm->num_pages == vma_pages(vma));
1255 	for (i = 0; i < bo->ttm.ttm->num_pages; i++) {
1256 		ret = remap_pfn_range(vma, start, page_to_pfn(bo->ttm.ttm->pages[i]),
1257 				      PAGE_SIZE, vma->vm_page_prot);
1258 		if (ret)
1259 			break;
1260 
1261 		start += PAGE_SIZE;
1262 	}
1263 
1264 	return ret;
1265 }
1266 
1267 static const struct file_operations xe_oa_fops = {
1268 	.owner		= THIS_MODULE,
1269 	.release	= xe_oa_release,
1270 	.poll		= xe_oa_poll,
1271 	.read		= xe_oa_read,
1272 	.unlocked_ioctl	= xe_oa_ioctl,
1273 	.mmap		= xe_oa_mmap,
1274 };
1275 
1276 static bool engine_supports_mi_query(struct xe_hw_engine *hwe)
1277 {
1278 	return hwe->class == XE_ENGINE_CLASS_RENDER ||
1279 		hwe->class == XE_ENGINE_CLASS_COMPUTE;
1280 }
1281 
1282 static bool xe_oa_find_reg_in_lri(u32 *state, u32 reg, u32 *offset, u32 end)
1283 {
1284 	u32 idx = *offset;
1285 	u32 len = min(MI_LRI_LEN(state[idx]) + idx, end);
1286 	bool found = false;
1287 
1288 	idx++;
1289 	for (; idx < len; idx += 2) {
1290 		if (state[idx] == reg) {
1291 			found = true;
1292 			break;
1293 		}
1294 	}
1295 
1296 	*offset = idx;
1297 	return found;
1298 }
1299 
1300 #define IS_MI_LRI_CMD(x) (REG_FIELD_GET(MI_OPCODE, (x)) == \
1301 			  REG_FIELD_GET(MI_OPCODE, MI_LOAD_REGISTER_IMM))
1302 
1303 static u32 xe_oa_context_image_offset(struct xe_oa_stream *stream, u32 reg)
1304 {
1305 	struct xe_lrc *lrc = stream->exec_q->lrc[0];
1306 	u32 len = (xe_gt_lrc_size(stream->gt, stream->hwe->class) +
1307 		   lrc->ring.size) / sizeof(u32);
1308 	u32 offset = xe_lrc_regs_offset(lrc) / sizeof(u32);
1309 	u32 *state = (u32 *)lrc->bo->vmap.vaddr;
1310 
1311 	if (drm_WARN_ON(&stream->oa->xe->drm, !state))
1312 		return U32_MAX;
1313 
1314 	for (; offset < len; ) {
1315 		if (IS_MI_LRI_CMD(state[offset])) {
1316 			/*
1317 			 * We expect reg-value pairs in MI_LRI command, so
1318 			 * MI_LRI_LEN() should be even
1319 			 */
1320 			drm_WARN_ON(&stream->oa->xe->drm,
1321 				    MI_LRI_LEN(state[offset]) & 0x1);
1322 
1323 			if (xe_oa_find_reg_in_lri(state, reg, &offset, len))
1324 				break;
1325 		} else {
1326 			offset++;
1327 		}
1328 	}
1329 
1330 	return offset < len ? offset : U32_MAX;
1331 }
1332 
1333 static int xe_oa_set_ctx_ctrl_offset(struct xe_oa_stream *stream)
1334 {
1335 	struct xe_reg reg = OACTXCONTROL(stream->hwe->mmio_base);
1336 	u32 offset = stream->oa->ctx_oactxctrl_offset[stream->hwe->class];
1337 
1338 	/* Do this only once. Failure is stored as offset of U32_MAX */
1339 	if (offset)
1340 		goto exit;
1341 
1342 	offset = xe_oa_context_image_offset(stream, reg.addr);
1343 	stream->oa->ctx_oactxctrl_offset[stream->hwe->class] = offset;
1344 
1345 	drm_dbg(&stream->oa->xe->drm, "%s oa ctx control at 0x%08x dword offset\n",
1346 		stream->hwe->name, offset);
1347 exit:
1348 	return offset && offset != U32_MAX ? 0 : -ENODEV;
1349 }
1350 
1351 static int xe_oa_stream_init(struct xe_oa_stream *stream,
1352 			     struct xe_oa_open_param *param)
1353 {
1354 	struct xe_oa_unit *u = param->hwe->oa_unit;
1355 	struct xe_gt *gt = param->hwe->gt;
1356 	int ret;
1357 
1358 	stream->exec_q = param->exec_q;
1359 	stream->poll_period_ns = DEFAULT_POLL_PERIOD_NS;
1360 	stream->hwe = param->hwe;
1361 	stream->gt = stream->hwe->gt;
1362 	stream->oa_buffer.format = &stream->oa->oa_formats[param->oa_format];
1363 
1364 	stream->sample = param->sample;
1365 	stream->periodic = param->period_exponent > 0;
1366 	stream->period_exponent = param->period_exponent;
1367 	stream->no_preempt = param->no_preempt;
1368 
1369 	/*
1370 	 * For Xe2+, when overrun mode is enabled, there are no partial reports at the end
1371 	 * of buffer, making the OA buffer effectively a non-power-of-2 size circular
1372 	 * buffer whose size, circ_size, is a multiple of the report size
1373 	 */
1374 	if (GRAPHICS_VER(stream->oa->xe) >= 20 &&
1375 	    stream->hwe->oa_unit->type == DRM_XE_OA_UNIT_TYPE_OAG && stream->sample)
1376 		stream->oa_buffer.circ_size =
1377 			XE_OA_BUFFER_SIZE - XE_OA_BUFFER_SIZE % stream->oa_buffer.format->size;
1378 	else
1379 		stream->oa_buffer.circ_size = XE_OA_BUFFER_SIZE;
1380 
1381 	if (stream->exec_q && engine_supports_mi_query(stream->hwe)) {
1382 		/* If we don't find the context offset, just return error */
1383 		ret = xe_oa_set_ctx_ctrl_offset(stream);
1384 		if (ret) {
1385 			drm_err(&stream->oa->xe->drm,
1386 				"xe_oa_set_ctx_ctrl_offset failed for %s\n",
1387 				stream->hwe->name);
1388 			goto exit;
1389 		}
1390 	}
1391 
1392 	stream->oa_config = xe_oa_get_oa_config(stream->oa, param->metric_set);
1393 	if (!stream->oa_config) {
1394 		drm_dbg(&stream->oa->xe->drm, "Invalid OA config id=%i\n", param->metric_set);
1395 		ret = -EINVAL;
1396 		goto exit;
1397 	}
1398 
1399 	/*
1400 	 * Wa_1509372804:pvc
1401 	 *
1402 	 * GuC reset of engines causes OA to lose configuration
1403 	 * state. Prevent this by overriding GUCRC mode.
1404 	 */
1405 	if (stream->oa->xe->info.platform == XE_PVC) {
1406 		ret = xe_guc_pc_override_gucrc_mode(&gt->uc.guc.pc,
1407 						    SLPC_GUCRC_MODE_GUCRC_NO_RC6);
1408 		if (ret)
1409 			goto err_free_configs;
1410 
1411 		stream->override_gucrc = true;
1412 	}
1413 
1414 	/* Take runtime pm ref and forcewake to disable RC6 */
1415 	xe_pm_runtime_get(stream->oa->xe);
1416 	XE_WARN_ON(xe_force_wake_get(gt_to_fw(gt), XE_FORCEWAKE_ALL));
1417 
1418 	ret = xe_oa_alloc_oa_buffer(stream);
1419 	if (ret)
1420 		goto err_fw_put;
1421 
1422 	stream->k_exec_q = xe_exec_queue_create(stream->oa->xe, NULL,
1423 						BIT(stream->hwe->logical_instance), 1,
1424 						stream->hwe, EXEC_QUEUE_FLAG_KERNEL, 0);
1425 	if (IS_ERR(stream->k_exec_q)) {
1426 		ret = PTR_ERR(stream->k_exec_q);
1427 		drm_err(&stream->oa->xe->drm, "gt%d, hwe %s, xe_exec_queue_create failed=%d",
1428 			stream->gt->info.id, stream->hwe->name, ret);
1429 		goto err_free_oa_buf;
1430 	}
1431 
1432 	ret = xe_oa_enable_metric_set(stream);
1433 	if (ret) {
1434 		drm_dbg(&stream->oa->xe->drm, "Unable to enable metric set\n");
1435 		goto err_put_k_exec_q;
1436 	}
1437 
1438 	drm_dbg(&stream->oa->xe->drm, "opening stream oa config uuid=%s\n",
1439 		stream->oa_config->uuid);
1440 
1441 	WRITE_ONCE(u->exclusive_stream, stream);
1442 
1443 	hrtimer_init(&stream->poll_check_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1444 	stream->poll_check_timer.function = xe_oa_poll_check_timer_cb;
1445 	init_waitqueue_head(&stream->poll_wq);
1446 
1447 	spin_lock_init(&stream->oa_buffer.ptr_lock);
1448 	mutex_init(&stream->stream_lock);
1449 
1450 	return 0;
1451 
1452 err_put_k_exec_q:
1453 	xe_oa_disable_metric_set(stream);
1454 	xe_exec_queue_put(stream->k_exec_q);
1455 err_free_oa_buf:
1456 	xe_oa_free_oa_buffer(stream);
1457 err_fw_put:
1458 	XE_WARN_ON(xe_force_wake_put(gt_to_fw(gt), XE_FORCEWAKE_ALL));
1459 	xe_pm_runtime_put(stream->oa->xe);
1460 	if (stream->override_gucrc)
1461 		xe_gt_WARN_ON(gt, xe_guc_pc_unset_gucrc_mode(&gt->uc.guc.pc));
1462 err_free_configs:
1463 	xe_oa_free_configs(stream);
1464 exit:
1465 	return ret;
1466 }
1467 
1468 static int xe_oa_stream_open_ioctl_locked(struct xe_oa *oa,
1469 					  struct xe_oa_open_param *param)
1470 {
1471 	struct xe_oa_stream *stream;
1472 	int stream_fd;
1473 	int ret;
1474 
1475 	/* We currently only allow exclusive access */
1476 	if (param->hwe->oa_unit->exclusive_stream) {
1477 		drm_dbg(&oa->xe->drm, "OA unit already in use\n");
1478 		ret = -EBUSY;
1479 		goto exit;
1480 	}
1481 
1482 	stream = kzalloc(sizeof(*stream), GFP_KERNEL);
1483 	if (!stream) {
1484 		ret = -ENOMEM;
1485 		goto exit;
1486 	}
1487 
1488 	stream->oa = oa;
1489 	ret = xe_oa_stream_init(stream, param);
1490 	if (ret)
1491 		goto err_free;
1492 
1493 	if (!param->disabled) {
1494 		ret = xe_oa_enable_locked(stream);
1495 		if (ret)
1496 			goto err_destroy;
1497 	}
1498 
1499 	stream_fd = anon_inode_getfd("[xe_oa]", &xe_oa_fops, stream, 0);
1500 	if (stream_fd < 0) {
1501 		ret = stream_fd;
1502 		goto err_disable;
1503 	}
1504 
1505 	/* Hold a reference on the drm device till stream_fd is released */
1506 	drm_dev_get(&stream->oa->xe->drm);
1507 
1508 	return stream_fd;
1509 err_disable:
1510 	if (!param->disabled)
1511 		xe_oa_disable_locked(stream);
1512 err_destroy:
1513 	xe_oa_stream_destroy(stream);
1514 err_free:
1515 	kfree(stream);
1516 exit:
1517 	return ret;
1518 }
1519 
1520 /**
1521  * xe_oa_timestamp_frequency - Return OA timestamp frequency
1522  * @gt: @xe_gt
1523  *
1524  * OA timestamp frequency = CS timestamp frequency in most platforms. On some
1525  * platforms OA unit ignores the CTC_SHIFT and the 2 timestamps differ. In such
1526  * cases, return the adjusted CS timestamp frequency to the user.
1527  */
1528 u32 xe_oa_timestamp_frequency(struct xe_gt *gt)
1529 {
1530 	u32 reg, shift;
1531 
1532 	/*
1533 	 * Wa_18013179988:dg2
1534 	 * Wa_14015568240:pvc
1535 	 * Wa_14015846243:mtl
1536 	 */
1537 	switch (gt_to_xe(gt)->info.platform) {
1538 	case XE_DG2:
1539 	case XE_PVC:
1540 	case XE_METEORLAKE:
1541 		xe_pm_runtime_get(gt_to_xe(gt));
1542 		reg = xe_mmio_read32(&gt->mmio, RPM_CONFIG0);
1543 		xe_pm_runtime_put(gt_to_xe(gt));
1544 
1545 		shift = REG_FIELD_GET(RPM_CONFIG0_CTC_SHIFT_PARAMETER_MASK, reg);
1546 		return gt->info.reference_clock << (3 - shift);
1547 
1548 	default:
1549 		return gt->info.reference_clock;
1550 	}
1551 }
1552 
1553 static u64 oa_exponent_to_ns(struct xe_gt *gt, int exponent)
1554 {
1555 	u64 nom = (2ULL << exponent) * NSEC_PER_SEC;
1556 	u32 den = xe_oa_timestamp_frequency(gt);
1557 
1558 	return div_u64(nom + den - 1, den);
1559 }
1560 
1561 static bool engine_supports_oa_format(const struct xe_hw_engine *hwe, int type)
1562 {
1563 	switch (hwe->oa_unit->type) {
1564 	case DRM_XE_OA_UNIT_TYPE_OAG:
1565 		return type == DRM_XE_OA_FMT_TYPE_OAG || type == DRM_XE_OA_FMT_TYPE_OAR ||
1566 			type == DRM_XE_OA_FMT_TYPE_OAC || type == DRM_XE_OA_FMT_TYPE_PEC;
1567 	case DRM_XE_OA_UNIT_TYPE_OAM:
1568 		return type == DRM_XE_OA_FMT_TYPE_OAM || type == DRM_XE_OA_FMT_TYPE_OAM_MPEC;
1569 	default:
1570 		return false;
1571 	}
1572 }
1573 
1574 static int decode_oa_format(struct xe_oa *oa, u64 fmt, enum xe_oa_format_name *name)
1575 {
1576 	u32 counter_size = FIELD_GET(DRM_XE_OA_FORMAT_MASK_COUNTER_SIZE, fmt);
1577 	u32 counter_sel = FIELD_GET(DRM_XE_OA_FORMAT_MASK_COUNTER_SEL, fmt);
1578 	u32 bc_report = FIELD_GET(DRM_XE_OA_FORMAT_MASK_BC_REPORT, fmt);
1579 	u32 type = FIELD_GET(DRM_XE_OA_FORMAT_MASK_FMT_TYPE, fmt);
1580 	int idx;
1581 
1582 	for_each_set_bit(idx, oa->format_mask, __XE_OA_FORMAT_MAX) {
1583 		const struct xe_oa_format *f = &oa->oa_formats[idx];
1584 
1585 		if (counter_size == f->counter_size && bc_report == f->bc_report &&
1586 		    type == f->type && counter_sel == f->counter_select) {
1587 			*name = idx;
1588 			return 0;
1589 		}
1590 	}
1591 
1592 	return -EINVAL;
1593 }
1594 
1595 /**
1596  * xe_oa_unit_id - Return OA unit ID for a hardware engine
1597  * @hwe: @xe_hw_engine
1598  *
1599  * Return OA unit ID for a hardware engine when available
1600  */
1601 u16 xe_oa_unit_id(struct xe_hw_engine *hwe)
1602 {
1603 	return hwe->oa_unit && hwe->oa_unit->num_engines ?
1604 		hwe->oa_unit->oa_unit_id : U16_MAX;
1605 }
1606 
1607 static int xe_oa_assign_hwe(struct xe_oa *oa, struct xe_oa_open_param *param)
1608 {
1609 	struct xe_gt *gt;
1610 	int i, ret = 0;
1611 
1612 	if (param->exec_q) {
1613 		/* When we have an exec_q, get hwe from the exec_q */
1614 		param->hwe = xe_gt_hw_engine(param->exec_q->gt, param->exec_q->class,
1615 					     param->engine_instance, true);
1616 	} else {
1617 		struct xe_hw_engine *hwe;
1618 		enum xe_hw_engine_id id;
1619 
1620 		/* Else just get the first hwe attached to the oa unit */
1621 		for_each_gt(gt, oa->xe, i) {
1622 			for_each_hw_engine(hwe, gt, id) {
1623 				if (xe_oa_unit_id(hwe) == param->oa_unit_id) {
1624 					param->hwe = hwe;
1625 					goto out;
1626 				}
1627 			}
1628 		}
1629 	}
1630 out:
1631 	if (!param->hwe || xe_oa_unit_id(param->hwe) != param->oa_unit_id) {
1632 		drm_dbg(&oa->xe->drm, "Unable to find hwe (%d, %d) for OA unit ID %d\n",
1633 			param->exec_q ? param->exec_q->class : -1,
1634 			param->engine_instance, param->oa_unit_id);
1635 		ret = -EINVAL;
1636 	}
1637 
1638 	return ret;
1639 }
1640 
1641 static int xe_oa_set_prop_oa_unit_id(struct xe_oa *oa, u64 value,
1642 				     struct xe_oa_open_param *param)
1643 {
1644 	if (value >= oa->oa_unit_ids) {
1645 		drm_dbg(&oa->xe->drm, "OA unit ID out of range %lld\n", value);
1646 		return -EINVAL;
1647 	}
1648 	param->oa_unit_id = value;
1649 	return 0;
1650 }
1651 
1652 static int xe_oa_set_prop_sample_oa(struct xe_oa *oa, u64 value,
1653 				    struct xe_oa_open_param *param)
1654 {
1655 	param->sample = value;
1656 	return 0;
1657 }
1658 
1659 static int xe_oa_set_prop_metric_set(struct xe_oa *oa, u64 value,
1660 				     struct xe_oa_open_param *param)
1661 {
1662 	param->metric_set = value;
1663 	return 0;
1664 }
1665 
1666 static int xe_oa_set_prop_oa_format(struct xe_oa *oa, u64 value,
1667 				    struct xe_oa_open_param *param)
1668 {
1669 	int ret = decode_oa_format(oa, value, &param->oa_format);
1670 
1671 	if (ret) {
1672 		drm_dbg(&oa->xe->drm, "Unsupported OA report format %#llx\n", value);
1673 		return ret;
1674 	}
1675 	return 0;
1676 }
1677 
1678 static int xe_oa_set_prop_oa_exponent(struct xe_oa *oa, u64 value,
1679 				      struct xe_oa_open_param *param)
1680 {
1681 #define OA_EXPONENT_MAX 31
1682 
1683 	if (value > OA_EXPONENT_MAX) {
1684 		drm_dbg(&oa->xe->drm, "OA timer exponent too high (> %u)\n", OA_EXPONENT_MAX);
1685 		return -EINVAL;
1686 	}
1687 	param->period_exponent = value;
1688 	return 0;
1689 }
1690 
1691 static int xe_oa_set_prop_disabled(struct xe_oa *oa, u64 value,
1692 				   struct xe_oa_open_param *param)
1693 {
1694 	param->disabled = value;
1695 	return 0;
1696 }
1697 
1698 static int xe_oa_set_prop_exec_queue_id(struct xe_oa *oa, u64 value,
1699 					struct xe_oa_open_param *param)
1700 {
1701 	param->exec_queue_id = value;
1702 	return 0;
1703 }
1704 
1705 static int xe_oa_set_prop_engine_instance(struct xe_oa *oa, u64 value,
1706 					  struct xe_oa_open_param *param)
1707 {
1708 	param->engine_instance = value;
1709 	return 0;
1710 }
1711 
1712 static int xe_oa_set_no_preempt(struct xe_oa *oa, u64 value,
1713 				struct xe_oa_open_param *param)
1714 {
1715 	param->no_preempt = value;
1716 	return 0;
1717 }
1718 
1719 typedef int (*xe_oa_set_property_fn)(struct xe_oa *oa, u64 value,
1720 				     struct xe_oa_open_param *param);
1721 static const xe_oa_set_property_fn xe_oa_set_property_funcs[] = {
1722 	[DRM_XE_OA_PROPERTY_OA_UNIT_ID] = xe_oa_set_prop_oa_unit_id,
1723 	[DRM_XE_OA_PROPERTY_SAMPLE_OA] = xe_oa_set_prop_sample_oa,
1724 	[DRM_XE_OA_PROPERTY_OA_METRIC_SET] = xe_oa_set_prop_metric_set,
1725 	[DRM_XE_OA_PROPERTY_OA_FORMAT] = xe_oa_set_prop_oa_format,
1726 	[DRM_XE_OA_PROPERTY_OA_PERIOD_EXPONENT] = xe_oa_set_prop_oa_exponent,
1727 	[DRM_XE_OA_PROPERTY_OA_DISABLED] = xe_oa_set_prop_disabled,
1728 	[DRM_XE_OA_PROPERTY_EXEC_QUEUE_ID] = xe_oa_set_prop_exec_queue_id,
1729 	[DRM_XE_OA_PROPERTY_OA_ENGINE_INSTANCE] = xe_oa_set_prop_engine_instance,
1730 	[DRM_XE_OA_PROPERTY_NO_PREEMPT] = xe_oa_set_no_preempt,
1731 };
1732 
1733 static int xe_oa_user_ext_set_property(struct xe_oa *oa, u64 extension,
1734 				       struct xe_oa_open_param *param)
1735 {
1736 	u64 __user *address = u64_to_user_ptr(extension);
1737 	struct drm_xe_ext_set_property ext;
1738 	int err;
1739 	u32 idx;
1740 
1741 	err = __copy_from_user(&ext, address, sizeof(ext));
1742 	if (XE_IOCTL_DBG(oa->xe, err))
1743 		return -EFAULT;
1744 
1745 	if (XE_IOCTL_DBG(oa->xe, ext.property >= ARRAY_SIZE(xe_oa_set_property_funcs)) ||
1746 	    XE_IOCTL_DBG(oa->xe, ext.pad))
1747 		return -EINVAL;
1748 
1749 	idx = array_index_nospec(ext.property, ARRAY_SIZE(xe_oa_set_property_funcs));
1750 	return xe_oa_set_property_funcs[idx](oa, ext.value, param);
1751 }
1752 
1753 typedef int (*xe_oa_user_extension_fn)(struct xe_oa *oa, u64 extension,
1754 				       struct xe_oa_open_param *param);
1755 static const xe_oa_user_extension_fn xe_oa_user_extension_funcs[] = {
1756 	[DRM_XE_OA_EXTENSION_SET_PROPERTY] = xe_oa_user_ext_set_property,
1757 };
1758 
1759 #define MAX_USER_EXTENSIONS	16
1760 static int xe_oa_user_extensions(struct xe_oa *oa, u64 extension, int ext_number,
1761 				 struct xe_oa_open_param *param)
1762 {
1763 	u64 __user *address = u64_to_user_ptr(extension);
1764 	struct drm_xe_user_extension ext;
1765 	int err;
1766 	u32 idx;
1767 
1768 	if (XE_IOCTL_DBG(oa->xe, ext_number >= MAX_USER_EXTENSIONS))
1769 		return -E2BIG;
1770 
1771 	err = __copy_from_user(&ext, address, sizeof(ext));
1772 	if (XE_IOCTL_DBG(oa->xe, err))
1773 		return -EFAULT;
1774 
1775 	if (XE_IOCTL_DBG(oa->xe, ext.pad) ||
1776 	    XE_IOCTL_DBG(oa->xe, ext.name >= ARRAY_SIZE(xe_oa_user_extension_funcs)))
1777 		return -EINVAL;
1778 
1779 	idx = array_index_nospec(ext.name, ARRAY_SIZE(xe_oa_user_extension_funcs));
1780 	err = xe_oa_user_extension_funcs[idx](oa, extension, param);
1781 	if (XE_IOCTL_DBG(oa->xe, err))
1782 		return err;
1783 
1784 	if (ext.next_extension)
1785 		return xe_oa_user_extensions(oa, ext.next_extension, ++ext_number, param);
1786 
1787 	return 0;
1788 }
1789 
1790 /**
1791  * xe_oa_stream_open_ioctl - Opens an OA stream
1792  * @dev: @drm_device
1793  * @data: pointer to struct @drm_xe_oa_config
1794  * @file: @drm_file
1795  *
1796  * The functions opens an OA stream. An OA stream, opened with specified
1797  * properties, enables OA counter samples to be collected, either
1798  * periodically (time based sampling), or on request (using OA queries)
1799  */
1800 int xe_oa_stream_open_ioctl(struct drm_device *dev, u64 data, struct drm_file *file)
1801 {
1802 	struct xe_device *xe = to_xe_device(dev);
1803 	struct xe_oa *oa = &xe->oa;
1804 	struct xe_file *xef = to_xe_file(file);
1805 	struct xe_oa_open_param param = {};
1806 	const struct xe_oa_format *f;
1807 	bool privileged_op = true;
1808 	int ret;
1809 
1810 	if (!oa->xe) {
1811 		drm_dbg(&xe->drm, "xe oa interface not available for this system\n");
1812 		return -ENODEV;
1813 	}
1814 
1815 	ret = xe_oa_user_extensions(oa, data, 0, &param);
1816 	if (ret)
1817 		return ret;
1818 
1819 	if (param.exec_queue_id > 0) {
1820 		param.exec_q = xe_exec_queue_lookup(xef, param.exec_queue_id);
1821 		if (XE_IOCTL_DBG(oa->xe, !param.exec_q))
1822 			return -ENOENT;
1823 
1824 		if (param.exec_q->width > 1)
1825 			drm_dbg(&oa->xe->drm, "exec_q->width > 1, programming only exec_q->lrc[0]\n");
1826 	}
1827 
1828 	/*
1829 	 * Query based sampling (using MI_REPORT_PERF_COUNT) with OAR/OAC,
1830 	 * without global stream access, can be an unprivileged operation
1831 	 */
1832 	if (param.exec_q && !param.sample)
1833 		privileged_op = false;
1834 
1835 	if (param.no_preempt) {
1836 		if (!param.exec_q) {
1837 			drm_dbg(&oa->xe->drm, "Preemption disable without exec_q!\n");
1838 			ret = -EINVAL;
1839 			goto err_exec_q;
1840 		}
1841 		privileged_op = true;
1842 	}
1843 
1844 	if (privileged_op && xe_observation_paranoid && !perfmon_capable()) {
1845 		drm_dbg(&oa->xe->drm, "Insufficient privileges to open xe OA stream\n");
1846 		ret = -EACCES;
1847 		goto err_exec_q;
1848 	}
1849 
1850 	if (!param.exec_q && !param.sample) {
1851 		drm_dbg(&oa->xe->drm, "Only OA report sampling supported\n");
1852 		ret = -EINVAL;
1853 		goto err_exec_q;
1854 	}
1855 
1856 	ret = xe_oa_assign_hwe(oa, &param);
1857 	if (ret)
1858 		goto err_exec_q;
1859 
1860 	f = &oa->oa_formats[param.oa_format];
1861 	if (!param.oa_format || !f->size ||
1862 	    !engine_supports_oa_format(param.hwe, f->type)) {
1863 		drm_dbg(&oa->xe->drm, "Invalid OA format %d type %d size %d for class %d\n",
1864 			param.oa_format, f->type, f->size, param.hwe->class);
1865 		ret = -EINVAL;
1866 		goto err_exec_q;
1867 	}
1868 
1869 	if (param.period_exponent > 0) {
1870 		u64 oa_period, oa_freq_hz;
1871 
1872 		/* Requesting samples from OAG buffer is a privileged operation */
1873 		if (!param.sample) {
1874 			drm_dbg(&oa->xe->drm, "OA_EXPONENT specified without SAMPLE_OA\n");
1875 			ret = -EINVAL;
1876 			goto err_exec_q;
1877 		}
1878 		oa_period = oa_exponent_to_ns(param.hwe->gt, param.period_exponent);
1879 		oa_freq_hz = div64_u64(NSEC_PER_SEC, oa_period);
1880 		drm_dbg(&oa->xe->drm, "Using periodic sampling freq %lld Hz\n", oa_freq_hz);
1881 	}
1882 
1883 	mutex_lock(&param.hwe->gt->oa.gt_lock);
1884 	ret = xe_oa_stream_open_ioctl_locked(oa, &param);
1885 	mutex_unlock(&param.hwe->gt->oa.gt_lock);
1886 err_exec_q:
1887 	if (ret < 0 && param.exec_q)
1888 		xe_exec_queue_put(param.exec_q);
1889 	return ret;
1890 }
1891 
1892 static bool xe_oa_is_valid_flex_addr(struct xe_oa *oa, u32 addr)
1893 {
1894 	static const struct xe_reg flex_eu_regs[] = {
1895 		EU_PERF_CNTL0,
1896 		EU_PERF_CNTL1,
1897 		EU_PERF_CNTL2,
1898 		EU_PERF_CNTL3,
1899 		EU_PERF_CNTL4,
1900 		EU_PERF_CNTL5,
1901 		EU_PERF_CNTL6,
1902 	};
1903 	int i;
1904 
1905 	for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
1906 		if (flex_eu_regs[i].addr == addr)
1907 			return true;
1908 	}
1909 	return false;
1910 }
1911 
1912 static bool xe_oa_reg_in_range_table(u32 addr, const struct xe_mmio_range *table)
1913 {
1914 	while (table->start && table->end) {
1915 		if (addr >= table->start && addr <= table->end)
1916 			return true;
1917 
1918 		table++;
1919 	}
1920 
1921 	return false;
1922 }
1923 
1924 static const struct xe_mmio_range xehp_oa_b_counters[] = {
1925 	{ .start = 0xdc48, .end = 0xdc48 },	/* OAA_ENABLE_REG */
1926 	{ .start = 0xdd00, .end = 0xdd48 },	/* OAG_LCE0_0 - OAA_LENABLE_REG */
1927 	{}
1928 };
1929 
1930 static const struct xe_mmio_range gen12_oa_b_counters[] = {
1931 	{ .start = 0x2b2c, .end = 0x2b2c },	/* OAG_OA_PESS */
1932 	{ .start = 0xd900, .end = 0xd91c },	/* OAG_OASTARTTRIG[1-8] */
1933 	{ .start = 0xd920, .end = 0xd93c },	/* OAG_OAREPORTTRIG1[1-8] */
1934 	{ .start = 0xd940, .end = 0xd97c },	/* OAG_CEC[0-7][0-1] */
1935 	{ .start = 0xdc00, .end = 0xdc3c },	/* OAG_SCEC[0-7][0-1] */
1936 	{ .start = 0xdc40, .end = 0xdc40 },	/* OAG_SPCTR_CNF */
1937 	{ .start = 0xdc44, .end = 0xdc44 },	/* OAA_DBG_REG */
1938 	{}
1939 };
1940 
1941 static const struct xe_mmio_range mtl_oam_b_counters[] = {
1942 	{ .start = 0x393000, .end = 0x39301c },	/* OAM_STARTTRIG1[1-8] */
1943 	{ .start = 0x393020, .end = 0x39303c },	/* OAM_REPORTTRIG1[1-8] */
1944 	{ .start = 0x393040, .end = 0x39307c },	/* OAM_CEC[0-7][0-1] */
1945 	{ .start = 0x393200, .end = 0x39323C },	/* MPES[0-7] */
1946 	{}
1947 };
1948 
1949 static const struct xe_mmio_range xe2_oa_b_counters[] = {
1950 	{ .start = 0x393200, .end = 0x39323C },	/* MPES_0_MPES_SAG - MPES_7_UPPER_MPES_SAG */
1951 	{ .start = 0x394200, .end = 0x39423C },	/* MPES_0_MPES_SCMI0 - MPES_7_UPPER_MPES_SCMI0 */
1952 	{ .start = 0x394A00, .end = 0x394A3C },	/* MPES_0_MPES_SCMI1 - MPES_7_UPPER_MPES_SCMI1 */
1953 	{},
1954 };
1955 
1956 static bool xe_oa_is_valid_b_counter_addr(struct xe_oa *oa, u32 addr)
1957 {
1958 	return xe_oa_reg_in_range_table(addr, xehp_oa_b_counters) ||
1959 		xe_oa_reg_in_range_table(addr, gen12_oa_b_counters) ||
1960 		xe_oa_reg_in_range_table(addr, mtl_oam_b_counters) ||
1961 		(GRAPHICS_VER(oa->xe) >= 20 &&
1962 		 xe_oa_reg_in_range_table(addr, xe2_oa_b_counters));
1963 }
1964 
1965 static const struct xe_mmio_range mtl_oa_mux_regs[] = {
1966 	{ .start = 0x0d00, .end = 0x0d04 },	/* RPM_CONFIG[0-1] */
1967 	{ .start = 0x0d0c, .end = 0x0d2c },	/* NOA_CONFIG[0-8] */
1968 	{ .start = 0x9840, .end = 0x9840 },	/* GDT_CHICKEN_BITS */
1969 	{ .start = 0x9884, .end = 0x9888 },	/* NOA_WRITE */
1970 	{ .start = 0x38d100, .end = 0x38d114},	/* VISACTL */
1971 	{}
1972 };
1973 
1974 static const struct xe_mmio_range gen12_oa_mux_regs[] = {
1975 	{ .start = 0x0d00, .end = 0x0d04 },     /* RPM_CONFIG[0-1] */
1976 	{ .start = 0x0d0c, .end = 0x0d2c },     /* NOA_CONFIG[0-8] */
1977 	{ .start = 0x9840, .end = 0x9840 },	/* GDT_CHICKEN_BITS */
1978 	{ .start = 0x9884, .end = 0x9888 },	/* NOA_WRITE */
1979 	{ .start = 0x20cc, .end = 0x20cc },	/* WAIT_FOR_RC6_EXIT */
1980 	{}
1981 };
1982 
1983 static const struct xe_mmio_range xe2_oa_mux_regs[] = {
1984 	{ .start = 0x5194, .end = 0x5194 },	/* SYS_MEM_LAT_MEASURE_MERTF_GRP_3D */
1985 	{ .start = 0x8704, .end = 0x8704 },	/* LMEM_LAT_MEASURE_MCFG_GRP */
1986 	{ .start = 0xB1BC, .end = 0xB1BC },	/* L3_BANK_LAT_MEASURE_LBCF_GFX */
1987 	{ .start = 0xE18C, .end = 0xE18C },	/* SAMPLER_MODE */
1988 	{ .start = 0xE590, .end = 0xE590 },	/* TDL_LSC_LAT_MEASURE_TDL_GFX */
1989 	{ .start = 0x13000, .end = 0x137FC },	/* PES_0_PESL0 - PES_63_UPPER_PESL3 */
1990 	{},
1991 };
1992 
1993 static bool xe_oa_is_valid_mux_addr(struct xe_oa *oa, u32 addr)
1994 {
1995 	if (GRAPHICS_VER(oa->xe) >= 20)
1996 		return xe_oa_reg_in_range_table(addr, xe2_oa_mux_regs);
1997 	else if (GRAPHICS_VERx100(oa->xe) >= 1270)
1998 		return xe_oa_reg_in_range_table(addr, mtl_oa_mux_regs);
1999 	else
2000 		return xe_oa_reg_in_range_table(addr, gen12_oa_mux_regs);
2001 }
2002 
2003 static bool xe_oa_is_valid_config_reg_addr(struct xe_oa *oa, u32 addr)
2004 {
2005 	return xe_oa_is_valid_flex_addr(oa, addr) ||
2006 		xe_oa_is_valid_b_counter_addr(oa, addr) ||
2007 		xe_oa_is_valid_mux_addr(oa, addr);
2008 }
2009 
2010 static struct xe_oa_reg *
2011 xe_oa_alloc_regs(struct xe_oa *oa, bool (*is_valid)(struct xe_oa *oa, u32 addr),
2012 		 u32 __user *regs, u32 n_regs)
2013 {
2014 	struct xe_oa_reg *oa_regs;
2015 	int err;
2016 	u32 i;
2017 
2018 	oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
2019 	if (!oa_regs)
2020 		return ERR_PTR(-ENOMEM);
2021 
2022 	for (i = 0; i < n_regs; i++) {
2023 		u32 addr, value;
2024 
2025 		err = get_user(addr, regs);
2026 		if (err)
2027 			goto addr_err;
2028 
2029 		if (!is_valid(oa, addr)) {
2030 			drm_dbg(&oa->xe->drm, "Invalid oa_reg address: %X\n", addr);
2031 			err = -EINVAL;
2032 			goto addr_err;
2033 		}
2034 
2035 		err = get_user(value, regs + 1);
2036 		if (err)
2037 			goto addr_err;
2038 
2039 		oa_regs[i].addr = XE_REG(addr);
2040 		oa_regs[i].value = value;
2041 
2042 		regs += 2;
2043 	}
2044 
2045 	return oa_regs;
2046 
2047 addr_err:
2048 	kfree(oa_regs);
2049 	return ERR_PTR(err);
2050 }
2051 
2052 static ssize_t show_dynamic_id(struct kobject *kobj,
2053 			       struct kobj_attribute *attr,
2054 			       char *buf)
2055 {
2056 	struct xe_oa_config *oa_config =
2057 		container_of(attr, typeof(*oa_config), sysfs_metric_id);
2058 
2059 	return sysfs_emit(buf, "%d\n", oa_config->id);
2060 }
2061 
2062 static int create_dynamic_oa_sysfs_entry(struct xe_oa *oa,
2063 					 struct xe_oa_config *oa_config)
2064 {
2065 	sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
2066 	oa_config->sysfs_metric_id.attr.name = "id";
2067 	oa_config->sysfs_metric_id.attr.mode = 0444;
2068 	oa_config->sysfs_metric_id.show = show_dynamic_id;
2069 	oa_config->sysfs_metric_id.store = NULL;
2070 
2071 	oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
2072 	oa_config->attrs[1] = NULL;
2073 
2074 	oa_config->sysfs_metric.name = oa_config->uuid;
2075 	oa_config->sysfs_metric.attrs = oa_config->attrs;
2076 
2077 	return sysfs_create_group(oa->metrics_kobj, &oa_config->sysfs_metric);
2078 }
2079 
2080 /**
2081  * xe_oa_add_config_ioctl - Adds one OA config
2082  * @dev: @drm_device
2083  * @data: pointer to struct @drm_xe_oa_config
2084  * @file: @drm_file
2085  *
2086  * The functions adds an OA config to the set of OA configs maintained in
2087  * the kernel. The config determines which OA metrics are collected for an
2088  * OA stream.
2089  */
2090 int xe_oa_add_config_ioctl(struct drm_device *dev, u64 data, struct drm_file *file)
2091 {
2092 	struct xe_device *xe = to_xe_device(dev);
2093 	struct xe_oa *oa = &xe->oa;
2094 	struct drm_xe_oa_config param;
2095 	struct drm_xe_oa_config *arg = &param;
2096 	struct xe_oa_config *oa_config, *tmp;
2097 	struct xe_oa_reg *regs;
2098 	int err, id;
2099 
2100 	if (!oa->xe) {
2101 		drm_dbg(&xe->drm, "xe oa interface not available for this system\n");
2102 		return -ENODEV;
2103 	}
2104 
2105 	if (xe_observation_paranoid && !perfmon_capable()) {
2106 		drm_dbg(&oa->xe->drm, "Insufficient privileges to add xe OA config\n");
2107 		return -EACCES;
2108 	}
2109 
2110 	err = __copy_from_user(&param, u64_to_user_ptr(data), sizeof(param));
2111 	if (XE_IOCTL_DBG(oa->xe, err))
2112 		return -EFAULT;
2113 
2114 	if (XE_IOCTL_DBG(oa->xe, arg->extensions) ||
2115 	    XE_IOCTL_DBG(oa->xe, !arg->regs_ptr) ||
2116 	    XE_IOCTL_DBG(oa->xe, !arg->n_regs))
2117 		return -EINVAL;
2118 
2119 	oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
2120 	if (!oa_config)
2121 		return -ENOMEM;
2122 
2123 	oa_config->oa = oa;
2124 	kref_init(&oa_config->ref);
2125 
2126 	if (!uuid_is_valid(arg->uuid)) {
2127 		drm_dbg(&oa->xe->drm, "Invalid uuid format for OA config\n");
2128 		err = -EINVAL;
2129 		goto reg_err;
2130 	}
2131 
2132 	/* Last character in oa_config->uuid will be 0 because oa_config is kzalloc */
2133 	memcpy(oa_config->uuid, arg->uuid, sizeof(arg->uuid));
2134 
2135 	oa_config->regs_len = arg->n_regs;
2136 	regs = xe_oa_alloc_regs(oa, xe_oa_is_valid_config_reg_addr,
2137 				u64_to_user_ptr(arg->regs_ptr),
2138 				arg->n_regs);
2139 	if (IS_ERR(regs)) {
2140 		drm_dbg(&oa->xe->drm, "Failed to create OA config for mux_regs\n");
2141 		err = PTR_ERR(regs);
2142 		goto reg_err;
2143 	}
2144 	oa_config->regs = regs;
2145 
2146 	err = mutex_lock_interruptible(&oa->metrics_lock);
2147 	if (err)
2148 		goto reg_err;
2149 
2150 	/* We shouldn't have too many configs, so this iteration shouldn't be too costly */
2151 	idr_for_each_entry(&oa->metrics_idr, tmp, id) {
2152 		if (!strcmp(tmp->uuid, oa_config->uuid)) {
2153 			drm_dbg(&oa->xe->drm, "OA config already exists with this uuid\n");
2154 			err = -EADDRINUSE;
2155 			goto sysfs_err;
2156 		}
2157 	}
2158 
2159 	err = create_dynamic_oa_sysfs_entry(oa, oa_config);
2160 	if (err) {
2161 		drm_dbg(&oa->xe->drm, "Failed to create sysfs entry for OA config\n");
2162 		goto sysfs_err;
2163 	}
2164 
2165 	oa_config->id = idr_alloc(&oa->metrics_idr, oa_config, 1, 0, GFP_KERNEL);
2166 	if (oa_config->id < 0) {
2167 		drm_dbg(&oa->xe->drm, "Failed to create sysfs entry for OA config\n");
2168 		err = oa_config->id;
2169 		goto sysfs_err;
2170 	}
2171 
2172 	mutex_unlock(&oa->metrics_lock);
2173 
2174 	drm_dbg(&oa->xe->drm, "Added config %s id=%i\n", oa_config->uuid, oa_config->id);
2175 
2176 	return oa_config->id;
2177 
2178 sysfs_err:
2179 	mutex_unlock(&oa->metrics_lock);
2180 reg_err:
2181 	xe_oa_config_put(oa_config);
2182 	drm_dbg(&oa->xe->drm, "Failed to add new OA config\n");
2183 	return err;
2184 }
2185 
2186 /**
2187  * xe_oa_remove_config_ioctl - Removes one OA config
2188  * @dev: @drm_device
2189  * @data: pointer to struct @drm_xe_observation_param
2190  * @file: @drm_file
2191  */
2192 int xe_oa_remove_config_ioctl(struct drm_device *dev, u64 data, struct drm_file *file)
2193 {
2194 	struct xe_device *xe = to_xe_device(dev);
2195 	struct xe_oa *oa = &xe->oa;
2196 	struct xe_oa_config *oa_config;
2197 	u64 arg, *ptr = u64_to_user_ptr(data);
2198 	int ret;
2199 
2200 	if (!oa->xe) {
2201 		drm_dbg(&xe->drm, "xe oa interface not available for this system\n");
2202 		return -ENODEV;
2203 	}
2204 
2205 	if (xe_observation_paranoid && !perfmon_capable()) {
2206 		drm_dbg(&oa->xe->drm, "Insufficient privileges to remove xe OA config\n");
2207 		return -EACCES;
2208 	}
2209 
2210 	ret = get_user(arg, ptr);
2211 	if (XE_IOCTL_DBG(oa->xe, ret))
2212 		return ret;
2213 
2214 	ret = mutex_lock_interruptible(&oa->metrics_lock);
2215 	if (ret)
2216 		return ret;
2217 
2218 	oa_config = idr_find(&oa->metrics_idr, arg);
2219 	if (!oa_config) {
2220 		drm_dbg(&oa->xe->drm, "Failed to remove unknown OA config\n");
2221 		ret = -ENOENT;
2222 		goto err_unlock;
2223 	}
2224 
2225 	WARN_ON(arg != oa_config->id);
2226 
2227 	sysfs_remove_group(oa->metrics_kobj, &oa_config->sysfs_metric);
2228 	idr_remove(&oa->metrics_idr, arg);
2229 
2230 	mutex_unlock(&oa->metrics_lock);
2231 
2232 	drm_dbg(&oa->xe->drm, "Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
2233 
2234 	xe_oa_config_put(oa_config);
2235 
2236 	return 0;
2237 
2238 err_unlock:
2239 	mutex_unlock(&oa->metrics_lock);
2240 	return ret;
2241 }
2242 
2243 /**
2244  * xe_oa_register - Xe OA registration
2245  * @xe: @xe_device
2246  *
2247  * Exposes the metrics sysfs directory upon completion of module initialization
2248  */
2249 void xe_oa_register(struct xe_device *xe)
2250 {
2251 	struct xe_oa *oa = &xe->oa;
2252 
2253 	if (!oa->xe)
2254 		return;
2255 
2256 	oa->metrics_kobj = kobject_create_and_add("metrics",
2257 						  &xe->drm.primary->kdev->kobj);
2258 }
2259 
2260 /**
2261  * xe_oa_unregister - Xe OA de-registration
2262  * @xe: @xe_device
2263  */
2264 void xe_oa_unregister(struct xe_device *xe)
2265 {
2266 	struct xe_oa *oa = &xe->oa;
2267 
2268 	if (!oa->metrics_kobj)
2269 		return;
2270 
2271 	kobject_put(oa->metrics_kobj);
2272 	oa->metrics_kobj = NULL;
2273 }
2274 
2275 static u32 num_oa_units_per_gt(struct xe_gt *gt)
2276 {
2277 	return 1;
2278 }
2279 
2280 static u32 __hwe_oam_unit(struct xe_hw_engine *hwe)
2281 {
2282 	if (GRAPHICS_VERx100(gt_to_xe(hwe->gt)) >= 1270) {
2283 		/*
2284 		 * There's 1 SAMEDIA gt and 1 OAM per SAMEDIA gt. All media slices
2285 		 * within the gt use the same OAM. All MTL/LNL SKUs list 1 SA MEDIA
2286 		 */
2287 		xe_gt_WARN_ON(hwe->gt, hwe->gt->info.type != XE_GT_TYPE_MEDIA);
2288 
2289 		return 0;
2290 	}
2291 
2292 	return XE_OA_UNIT_INVALID;
2293 }
2294 
2295 static u32 __hwe_oa_unit(struct xe_hw_engine *hwe)
2296 {
2297 	switch (hwe->class) {
2298 	case XE_ENGINE_CLASS_RENDER:
2299 	case XE_ENGINE_CLASS_COMPUTE:
2300 		return 0;
2301 
2302 	case XE_ENGINE_CLASS_VIDEO_DECODE:
2303 	case XE_ENGINE_CLASS_VIDEO_ENHANCE:
2304 		return __hwe_oam_unit(hwe);
2305 
2306 	default:
2307 		return XE_OA_UNIT_INVALID;
2308 	}
2309 }
2310 
2311 static struct xe_oa_regs __oam_regs(u32 base)
2312 {
2313 	return (struct xe_oa_regs) {
2314 		base,
2315 		OAM_HEAD_POINTER(base),
2316 		OAM_TAIL_POINTER(base),
2317 		OAM_BUFFER(base),
2318 		OAM_CONTEXT_CONTROL(base),
2319 		OAM_CONTROL(base),
2320 		OAM_DEBUG(base),
2321 		OAM_STATUS(base),
2322 		OAM_CONTROL_COUNTER_SEL_MASK,
2323 	};
2324 }
2325 
2326 static struct xe_oa_regs __oag_regs(void)
2327 {
2328 	return (struct xe_oa_regs) {
2329 		0,
2330 		OAG_OAHEADPTR,
2331 		OAG_OATAILPTR,
2332 		OAG_OABUFFER,
2333 		OAG_OAGLBCTXCTRL,
2334 		OAG_OACONTROL,
2335 		OAG_OA_DEBUG,
2336 		OAG_OASTATUS,
2337 		OAG_OACONTROL_OA_COUNTER_SEL_MASK,
2338 	};
2339 }
2340 
2341 static void __xe_oa_init_oa_units(struct xe_gt *gt)
2342 {
2343 	const u32 mtl_oa_base[] = { 0x13000 };
2344 	int i, num_units = gt->oa.num_oa_units;
2345 
2346 	for (i = 0; i < num_units; i++) {
2347 		struct xe_oa_unit *u = &gt->oa.oa_unit[i];
2348 
2349 		if (gt->info.type != XE_GT_TYPE_MEDIA) {
2350 			u->regs = __oag_regs();
2351 			u->type = DRM_XE_OA_UNIT_TYPE_OAG;
2352 		} else if (GRAPHICS_VERx100(gt_to_xe(gt)) >= 1270) {
2353 			u->regs = __oam_regs(mtl_oa_base[i]);
2354 			u->type = DRM_XE_OA_UNIT_TYPE_OAM;
2355 		}
2356 
2357 		/* Ensure MMIO trigger remains disabled till there is a stream */
2358 		xe_mmio_write32(&gt->mmio, u->regs.oa_debug,
2359 				oag_configure_mmio_trigger(NULL, false));
2360 
2361 		/* Set oa_unit_ids now to ensure ids remain contiguous */
2362 		u->oa_unit_id = gt_to_xe(gt)->oa.oa_unit_ids++;
2363 	}
2364 }
2365 
2366 static int xe_oa_init_gt(struct xe_gt *gt)
2367 {
2368 	u32 num_oa_units = num_oa_units_per_gt(gt);
2369 	struct xe_hw_engine *hwe;
2370 	enum xe_hw_engine_id id;
2371 	struct xe_oa_unit *u;
2372 
2373 	u = drmm_kcalloc(&gt_to_xe(gt)->drm, num_oa_units, sizeof(*u), GFP_KERNEL);
2374 	if (!u)
2375 		return -ENOMEM;
2376 
2377 	for_each_hw_engine(hwe, gt, id) {
2378 		u32 index = __hwe_oa_unit(hwe);
2379 
2380 		hwe->oa_unit = NULL;
2381 		if (index < num_oa_units) {
2382 			u[index].num_engines++;
2383 			hwe->oa_unit = &u[index];
2384 		}
2385 	}
2386 
2387 	/*
2388 	 * Fused off engines can result in oa_unit's with num_engines == 0. These units
2389 	 * will appear in OA unit query, but no OA streams can be opened on them.
2390 	 */
2391 	gt->oa.num_oa_units = num_oa_units;
2392 	gt->oa.oa_unit = u;
2393 
2394 	__xe_oa_init_oa_units(gt);
2395 
2396 	drmm_mutex_init(&gt_to_xe(gt)->drm, &gt->oa.gt_lock);
2397 
2398 	return 0;
2399 }
2400 
2401 static int xe_oa_init_oa_units(struct xe_oa *oa)
2402 {
2403 	struct xe_gt *gt;
2404 	int i, ret;
2405 
2406 	for_each_gt(gt, oa->xe, i) {
2407 		ret = xe_oa_init_gt(gt);
2408 		if (ret)
2409 			return ret;
2410 	}
2411 
2412 	return 0;
2413 }
2414 
2415 static void oa_format_add(struct xe_oa *oa, enum xe_oa_format_name format)
2416 {
2417 	__set_bit(format, oa->format_mask);
2418 }
2419 
2420 static void xe_oa_init_supported_formats(struct xe_oa *oa)
2421 {
2422 	if (GRAPHICS_VER(oa->xe) >= 20) {
2423 		/* Xe2+ */
2424 		oa_format_add(oa, XE_OAM_FORMAT_MPEC8u64_B8_C8);
2425 		oa_format_add(oa, XE_OAM_FORMAT_MPEC8u32_B8_C8);
2426 		oa_format_add(oa, XE_OA_FORMAT_PEC64u64);
2427 		oa_format_add(oa, XE_OA_FORMAT_PEC64u64_B8_C8);
2428 		oa_format_add(oa, XE_OA_FORMAT_PEC64u32);
2429 		oa_format_add(oa, XE_OA_FORMAT_PEC32u64_G1);
2430 		oa_format_add(oa, XE_OA_FORMAT_PEC32u32_G1);
2431 		oa_format_add(oa, XE_OA_FORMAT_PEC32u64_G2);
2432 		oa_format_add(oa, XE_OA_FORMAT_PEC32u32_G2);
2433 		oa_format_add(oa, XE_OA_FORMAT_PEC36u64_G1_32_G2_4);
2434 		oa_format_add(oa, XE_OA_FORMAT_PEC36u64_G1_4_G2_32);
2435 	} else if (GRAPHICS_VERx100(oa->xe) >= 1270) {
2436 		/* XE_METEORLAKE */
2437 		oa_format_add(oa, XE_OAR_FORMAT_A32u40_A4u32_B8_C8);
2438 		oa_format_add(oa, XE_OA_FORMAT_A24u40_A14u32_B8_C8);
2439 		oa_format_add(oa, XE_OAC_FORMAT_A24u64_B8_C8);
2440 		oa_format_add(oa, XE_OAC_FORMAT_A22u32_R2u32_B8_C8);
2441 		oa_format_add(oa, XE_OAM_FORMAT_MPEC8u64_B8_C8);
2442 		oa_format_add(oa, XE_OAM_FORMAT_MPEC8u32_B8_C8);
2443 	} else if (GRAPHICS_VERx100(oa->xe) >= 1255) {
2444 		/* XE_DG2, XE_PVC */
2445 		oa_format_add(oa, XE_OAR_FORMAT_A32u40_A4u32_B8_C8);
2446 		oa_format_add(oa, XE_OA_FORMAT_A24u40_A14u32_B8_C8);
2447 		oa_format_add(oa, XE_OAC_FORMAT_A24u64_B8_C8);
2448 		oa_format_add(oa, XE_OAC_FORMAT_A22u32_R2u32_B8_C8);
2449 	} else {
2450 		/* Gen12+ */
2451 		xe_assert(oa->xe, GRAPHICS_VER(oa->xe) >= 12);
2452 		oa_format_add(oa, XE_OA_FORMAT_A12);
2453 		oa_format_add(oa, XE_OA_FORMAT_A12_B8_C8);
2454 		oa_format_add(oa, XE_OA_FORMAT_A32u40_A4u32_B8_C8);
2455 		oa_format_add(oa, XE_OA_FORMAT_C4_B8);
2456 	}
2457 }
2458 
2459 /**
2460  * xe_oa_init - OA initialization during device probe
2461  * @xe: @xe_device
2462  *
2463  * Return: 0 on success or a negative error code on failure
2464  */
2465 int xe_oa_init(struct xe_device *xe)
2466 {
2467 	struct xe_oa *oa = &xe->oa;
2468 	int ret;
2469 
2470 	/* Support OA only with GuC submission and Gen12+ */
2471 	if (!xe_device_uc_enabled(xe) || GRAPHICS_VER(xe) < 12)
2472 		return 0;
2473 
2474 	if (IS_SRIOV_VF(xe))
2475 		return 0;
2476 
2477 	oa->xe = xe;
2478 	oa->oa_formats = oa_formats;
2479 
2480 	drmm_mutex_init(&oa->xe->drm, &oa->metrics_lock);
2481 	idr_init_base(&oa->metrics_idr, 1);
2482 
2483 	ret = xe_oa_init_oa_units(oa);
2484 	if (ret) {
2485 		drm_err(&xe->drm, "OA initialization failed (%pe)\n", ERR_PTR(ret));
2486 		goto exit;
2487 	}
2488 
2489 	xe_oa_init_supported_formats(oa);
2490 	return 0;
2491 exit:
2492 	oa->xe = NULL;
2493 	return ret;
2494 }
2495 
2496 static int destroy_config(int id, void *p, void *data)
2497 {
2498 	xe_oa_config_put(p);
2499 	return 0;
2500 }
2501 
2502 /**
2503  * xe_oa_fini - OA de-initialization during device remove
2504  * @xe: @xe_device
2505  */
2506 void xe_oa_fini(struct xe_device *xe)
2507 {
2508 	struct xe_oa *oa = &xe->oa;
2509 
2510 	if (!oa->xe)
2511 		return;
2512 
2513 	idr_for_each(&oa->metrics_idr, destroy_config, oa);
2514 	idr_destroy(&oa->metrics_idr);
2515 
2516 	oa->xe = NULL;
2517 }
2518