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