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