xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c (revision e28daba76453f5e2180f557c7211d25c269a489f)
1 /*
2  * Copyright 2019 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  */
23 
24 #include <linux/firmware.h>
25 #include <linux/kthread.h>
26 #include <linux/delay.h>
27 #include <linux/sizes.h>
28 #include <linux/slab.h>
29 #include <linux/workqueue.h>
30 #include <drm/drm_exec.h>
31 
32 #include "amdgpu_mes.h"
33 #include "amdgpu.h"
34 #include "soc15_common.h"
35 #include "amdgpu_mes_ctx.h"
36 
37 #define AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS 1024
38 #define AMDGPU_ONE_DOORBELL_SIZE 8
39 
40 int amdgpu_mes_doorbell_process_slice(struct amdgpu_device *adev)
41 {
42 	return roundup(AMDGPU_ONE_DOORBELL_SIZE *
43 		       AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS,
44 		       PAGE_SIZE);
45 }
46 
47 static int amdgpu_mes_doorbell_init(struct amdgpu_device *adev)
48 {
49 	int i;
50 	struct amdgpu_mes *mes = &adev->mes;
51 
52 	/* Bitmap for dynamic allocation of kernel doorbells */
53 	mes->doorbell_bitmap = bitmap_zalloc(PAGE_SIZE / sizeof(u32), GFP_KERNEL);
54 	if (!mes->doorbell_bitmap) {
55 		dev_err(adev->dev, "Failed to allocate MES doorbell bitmap\n");
56 		return -ENOMEM;
57 	}
58 
59 	mes->num_mes_dbs = PAGE_SIZE / AMDGPU_ONE_DOORBELL_SIZE;
60 	for (i = 0; i < AMDGPU_MES_PRIORITY_NUM_LEVELS; i++) {
61 		adev->mes.aggregated_doorbells[i] = mes->db_start_dw_offset + i * 2;
62 		set_bit(i, mes->doorbell_bitmap);
63 	}
64 
65 	return 0;
66 }
67 
68 static int amdgpu_mes_event_log_init(struct amdgpu_device *adev)
69 {
70 	int r;
71 
72 	if (!amdgpu_mes_log_enable)
73 		return 0;
74 
75 	r = amdgpu_bo_create_kernel(adev, adev->mes.event_log_size, PAGE_SIZE,
76 				    AMDGPU_GEM_DOMAIN_VRAM,
77 				    &adev->mes.event_log_gpu_obj,
78 				    &adev->mes.event_log_gpu_addr,
79 				    &adev->mes.event_log_cpu_addr);
80 	if (r) {
81 		dev_warn(adev->dev, "failed to create MES event log buffer (%d)", r);
82 		return r;
83 	}
84 
85 	memset(adev->mes.event_log_cpu_addr, 0, adev->mes.event_log_size);
86 
87 	return  0;
88 
89 }
90 
91 static void amdgpu_mes_doorbell_free(struct amdgpu_device *adev)
92 {
93 	bitmap_free(adev->mes.doorbell_bitmap);
94 }
95 
96 static inline u32 amdgpu_mes_get_hqd_mask(u32 num_pipe,
97 					  u32 num_hqd_per_pipe,
98 					  u32 num_reserved_hqd)
99 {
100 	if (num_pipe == 0)
101 		return 0;
102 
103 	u32 total_hqd_mask = (u32)((1ULL << num_hqd_per_pipe) - 1);
104 	u32 reserved_hqd_mask = (u32)((1ULL << DIV_ROUND_UP(num_reserved_hqd, num_pipe)) - 1);
105 
106 	return (total_hqd_mask & ~reserved_hqd_mask);
107 }
108 
109 static void amdgpu_mes_userq_notify_unmap_work_handler(struct work_struct *work);
110 
111 int amdgpu_mes_init(struct amdgpu_device *adev)
112 {
113 	int i, r, num_pipes, num_queues = 0;
114 	int num_xcc = adev->gfx.xcc_mask ? NUM_XCC(adev->gfx.xcc_mask) : 1;
115 	u32 gfx_hqd_mask = amdgpu_mes_get_hqd_mask(adev->gfx.me.num_pipe_per_me,
116 				adev->gfx.me.num_queue_per_pipe,
117 				adev->gfx.disable_kq ? 0 : adev->gfx.num_gfx_rings);
118 	u32 compute_hqd_mask = amdgpu_mes_get_hqd_mask(adev->gfx.mec.num_pipe_per_mec,
119 				adev->gfx.mec.num_queue_per_pipe,
120 				adev->gfx.disable_kq ? 0 : adev->gfx.num_compute_rings);
121 
122 	adev->mes.adev = adev;
123 
124 	ida_init(&adev->mes.doorbell_ida);
125 	spin_lock_init(&adev->mes.queue_id_lock);
126 	mutex_init(&adev->mes.mutex_hidden);
127 	mutex_init(&adev->mes.dbgext_lock);
128 
129 	for (i = 0; i < AMDGPU_MAX_MES_PIPES * num_xcc; i++)
130 		spin_lock_init(&adev->mes.ring_lock[i]);
131 
132 	adev->mes.total_max_queue = AMDGPU_FENCE_MES_QUEUE_ID_MASK;
133 	atomic_set(&adev->mes.userq_hw_queue_count, 0);
134 	INIT_DELAYED_WORK(&adev->mes.userq_notify_unmap_work,
135 			  amdgpu_mes_userq_notify_unmap_work_handler);
136 	num_pipes = adev->gfx.me.num_pipe_per_me * adev->gfx.me.num_me;
137 	if (num_pipes > AMDGPU_MES_MAX_GFX_PIPES)
138 		dev_warn(adev->dev, "more gfx pipes than supported by MES! (%d vs %d)\n",
139 			 num_pipes, AMDGPU_MES_MAX_GFX_PIPES);
140 
141 	for (i = 0; i < AMDGPU_MES_MAX_GFX_PIPES; i++) {
142 		if (i >= num_pipes)
143 			break;
144 
145 		adev->mes.gfx_hqd_mask[i] = gfx_hqd_mask;
146 	}
147 
148 	num_pipes = adev->gfx.mec.num_pipe_per_mec * adev->gfx.mec.num_mec;
149 	if (num_pipes > AMDGPU_MES_MAX_COMPUTE_PIPES)
150 		dev_warn(adev->dev, "more compute pipes than supported by MES! (%d vs %d)\n",
151 			 num_pipes, AMDGPU_MES_MAX_COMPUTE_PIPES);
152 
153 	for (i = 0; i < AMDGPU_MES_MAX_COMPUTE_PIPES; i++) {
154 		/*
155 		 * Currently, only MEC1 is used for both kernel and user compute queue.
156 		 * To enable other MEC, we need to redistribute queues per pipe and
157 		 * adjust queue resource shared with kfd that needs a separate patch.
158 		 * Skip other MEC for now to avoid potential issues.
159 		 */
160 		if (i >= adev->gfx.mec.num_pipe_per_mec)
161 			break;
162 
163 		adev->mes.compute_hqd_mask[i] = compute_hqd_mask;
164 	}
165 
166 	num_pipes = adev->sdma.num_inst_per_xcc ?
167 		adev->sdma.num_inst_per_xcc : adev->sdma.num_instances;
168 	if (num_pipes > AMDGPU_MES_MAX_SDMA_PIPES)
169 		dev_warn(adev->dev, "more SDMA pipes than supported by MES! (%d vs %d)\n",
170 			 num_pipes, AMDGPU_MES_MAX_SDMA_PIPES);
171 
172 	for (i = 0; i < AMDGPU_MES_MAX_SDMA_PIPES; i++) {
173 		if (i >= num_pipes)
174 			break;
175 		adev->mes.sdma_hqd_mask[i] = 0xfc;
176 	}
177 
178 	dev_info(adev->dev,
179 			 "MES: vmid_uq_mask_mmhub 0x%08x, vmid_uq_mask_gfxhub 0x%08x\n",
180 			 adev->vm_manager.vmid_uq_mask_mmhub,
181 			 adev->vm_manager.vmid_uq_mask_gfxhub);
182 
183 	dev_info(adev->dev,
184 			 "MES: gfx_hqd_mask 0x%08x, compute_hqd_mask 0x%08x, sdma_hqd_mask 0x%08x\n",
185 			 adev->mes.gfx_hqd_mask[0],
186 			 adev->mes.compute_hqd_mask[0],
187 			 adev->mes.sdma_hqd_mask[0]);
188 
189 	for (i = 0; i < AMDGPU_MAX_MES_PIPES * num_xcc; i++) {
190 		r = amdgpu_wb_get(adev, &adev->mes.sch_ctx_offs[i]);
191 		if (r) {
192 			dev_err(adev->dev,
193 				"(%d) ring trail_fence_offs wb alloc failed\n",
194 				r);
195 			goto error;
196 		}
197 		adev->mes.sch_ctx_gpu_addr[i] =
198 			adev->wb.gpu_addr + (adev->mes.sch_ctx_offs[i] * 4);
199 		adev->mes.sch_ctx_ptr[i] =
200 			(uint64_t *)&adev->wb.wb[adev->mes.sch_ctx_offs[i]];
201 
202 		r = amdgpu_wb_get(adev,
203 				 &adev->mes.query_status_fence_offs[i]);
204 		if (r) {
205 			dev_err(adev->dev,
206 			      "(%d) query_status_fence_offs wb alloc failed\n",
207 			      r);
208 			goto error;
209 		}
210 		adev->mes.query_status_fence_gpu_addr[i] = adev->wb.gpu_addr +
211 			(adev->mes.query_status_fence_offs[i] * 4);
212 		adev->mes.query_status_fence_ptr[i] =
213 			(uint64_t *)&adev->wb.wb[adev->mes.query_status_fence_offs[i]];
214 	}
215 
216 	r = amdgpu_mes_doorbell_init(adev);
217 	if (r)
218 		goto error;
219 
220 	r = amdgpu_mes_event_log_init(adev);
221 	if (r)
222 		goto error_doorbell;
223 
224 	if (amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0)) {
225 		/* When queue/pipe reset is done in MES instead of in the
226 		 * driver, MES passes hung queues information to the driver in
227 		 * hung_queue_hqd_info. Calculate required space to store this
228 		 * information.
229 		 */
230 		for (i = 0; i < AMDGPU_MES_MAX_GFX_PIPES; i++)
231 			num_queues += hweight32(adev->mes.gfx_hqd_mask[i]);
232 
233 		for (i = 0; i < AMDGPU_MES_MAX_COMPUTE_PIPES; i++)
234 			num_queues += hweight32(adev->mes.compute_hqd_mask[i]);
235 
236 		for (i = 0; i < AMDGPU_MES_MAX_SDMA_PIPES; i++)
237 			num_queues += hweight32(adev->mes.sdma_hqd_mask[i]) * num_xcc;
238 
239 		adev->mes.hung_queue_hqd_info_offset = num_queues;
240 		adev->mes.hung_queue_db_array_size = num_queues * 2;
241 	}
242 
243 	if (adev->mes.hung_queue_db_array_size) {
244 		for (i = 0; i < AMDGPU_MAX_MES_PIPES * num_xcc; i++) {
245 			r = amdgpu_bo_create_kernel(adev,
246 						    adev->mes.hung_queue_db_array_size * sizeof(u32),
247 						    PAGE_SIZE,
248 						    AMDGPU_GEM_DOMAIN_GTT,
249 						    &adev->mes.hung_queue_db_array_gpu_obj[i],
250 						    &adev->mes.hung_queue_db_array_gpu_addr[i],
251 						    &adev->mes.hung_queue_db_array_cpu_addr[i]);
252 			if (r) {
253 				dev_warn(adev->dev, "failed to create MES hung db array buffer (%d)", r);
254 				goto error_doorbell;
255 			}
256 		}
257 
258 		adev->gfx.mec.mes_hung_db_array =
259 			kzalloc_objs(*adev->gfx.mec.mes_hung_db_array,
260 				     amdgpu_mes_get_hung_queue_db_array_size(adev));
261 
262 		if (!adev->gfx.mec.mes_hung_db_array) {
263 			r = -ENOMEM;
264 			goto error_doorbell;
265 		}
266 	}
267 
268 	return 0;
269 
270 error_doorbell:
271 	amdgpu_mes_doorbell_free(adev);
272 error:
273 	for (i = 0; i < AMDGPU_MAX_MES_PIPES * num_xcc; i++) {
274 		if (adev->mes.sch_ctx_ptr[i])
275 			amdgpu_wb_free(adev, adev->mes.sch_ctx_offs[i]);
276 		if (adev->mes.query_status_fence_ptr[i])
277 			amdgpu_wb_free(adev,
278 				      adev->mes.query_status_fence_offs[i]);
279 		if (adev->mes.hung_queue_db_array_gpu_obj[i])
280 			amdgpu_bo_free_kernel(&adev->mes.hung_queue_db_array_gpu_obj[i],
281 					      &adev->mes.hung_queue_db_array_gpu_addr[i],
282 					      &adev->mes.hung_queue_db_array_cpu_addr[i]);
283 	}
284 
285 	ida_destroy(&adev->mes.doorbell_ida);
286 	mutex_destroy(&adev->mes.mutex_hidden);
287 	return r;
288 }
289 
290 void amdgpu_mes_fini(struct amdgpu_device *adev)
291 {
292 	int i;
293 	int num_xcc = adev->gfx.xcc_mask ? NUM_XCC(adev->gfx.xcc_mask) : 1;
294 
295 	cancel_delayed_work_sync(&adev->mes.userq_notify_unmap_work);
296 
297 	kfree(adev->gfx.mec.mes_hung_db_array);
298 
299 	amdgpu_bo_free_kernel(&adev->mes.event_log_gpu_obj,
300 			      &adev->mes.event_log_gpu_addr,
301 			      &adev->mes.event_log_cpu_addr);
302 
303 	for (i = 0; i < AMDGPU_MAX_MES_PIPES * num_xcc; i++) {
304 		if (adev->mes.hung_queue_db_array_gpu_obj[i])
305 			 amdgpu_bo_free_kernel(&adev->mes.hung_queue_db_array_gpu_obj[i],
306 					 &adev->mes.hung_queue_db_array_gpu_addr[i],
307 					 &adev->mes.hung_queue_db_array_cpu_addr[i]);
308 		if (adev->mes.sch_ctx_ptr[i])
309 			amdgpu_wb_free(adev, adev->mes.sch_ctx_offs[i]);
310 		if (adev->mes.query_status_fence_ptr[i])
311 			amdgpu_wb_free(adev,
312 				      adev->mes.query_status_fence_offs[i]);
313 	}
314 
315 	amdgpu_mes_doorbell_free(adev);
316 
317 	if (adev->mes.use_rs64mem)
318 		amdgpu_mes_rs64mem_fini(&adev->mes);
319 
320 	ida_destroy(&adev->mes.doorbell_ida);
321 	mutex_destroy(&adev->mes.mutex_hidden);
322 	mutex_destroy(&adev->mes.dbgext_lock);
323 }
324 
325 int amdgpu_mes_suspend(struct amdgpu_device *adev, u32 xcc_id)
326 {
327 	struct mes_suspend_gang_input input;
328 	int r;
329 
330 	if (!amdgpu_mes_suspend_resume_all_supported(adev))
331 		return 0;
332 
333 	memset(&input, 0x0, sizeof(struct mes_suspend_gang_input));
334 	input.suspend_all_gangs = 1;
335 	input.xcc_id = xcc_id;
336 	if ((amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(12, 1, 0)) &&
337 		((adev->mes.sched_version & AMDGPU_MES_VERSION_MASK) >= 0x71))
338 		input.suspend_all_sdma_gangs = 1;
339 
340 	/*
341 	 * Avoid taking any other locks under MES lock to avoid circular
342 	 * lock dependencies.
343 	 */
344 	amdgpu_mes_lock(&adev->mes);
345 	r = adev->mes.funcs->suspend_gang(&adev->mes, &input);
346 	amdgpu_mes_unlock(&adev->mes);
347 	if (r)
348 		dev_err(adev->dev, "failed to suspend all gangs");
349 
350 	return r;
351 }
352 
353 int amdgpu_mes_resume(struct amdgpu_device *adev, u32 xcc_id)
354 {
355 	struct mes_resume_gang_input input;
356 	int r;
357 
358 	if (!amdgpu_mes_suspend_resume_all_supported(adev))
359 		return 0;
360 
361 	memset(&input, 0x0, sizeof(struct mes_resume_gang_input));
362 	input.resume_all_gangs = 1;
363 	input.xcc_id = xcc_id;
364 
365 	/*
366 	 * Avoid taking any other locks under MES lock to avoid circular
367 	 * lock dependencies.
368 	 */
369 	amdgpu_mes_lock(&adev->mes);
370 	r = adev->mes.funcs->resume_gang(&adev->mes, &input);
371 	amdgpu_mes_unlock(&adev->mes);
372 	if (r)
373 		dev_err(adev->dev, "failed to resume all gangs");
374 
375 	return r;
376 }
377 
378 int amdgpu_mes_map_legacy_queue(struct amdgpu_device *adev,
379 				struct amdgpu_ring *ring, uint32_t xcc_id)
380 {
381 	struct mes_map_legacy_queue_input queue_input;
382 	int r;
383 
384 	memset(&queue_input, 0, sizeof(queue_input));
385 
386 	queue_input.xcc_id = xcc_id;
387 	queue_input.queue_type = ring->funcs->type;
388 	queue_input.doorbell_offset = ring->doorbell_index;
389 	queue_input.pipe_id = ring->pipe;
390 	queue_input.queue_id = ring->queue;
391 	queue_input.mqd_addr = amdgpu_bo_gpu_offset(ring->mqd_obj);
392 	queue_input.wptr_addr = ring->wptr_gpu_addr;
393 
394 	amdgpu_mes_lock(&adev->mes);
395 	r = adev->mes.funcs->map_legacy_queue(&adev->mes, &queue_input);
396 	amdgpu_mes_unlock(&adev->mes);
397 	if (r)
398 		dev_err(adev->dev, "failed to map legacy queue\n");
399 
400 	return r;
401 }
402 
403 int amdgpu_mes_unmap_legacy_queue(struct amdgpu_device *adev,
404 				  struct amdgpu_ring *ring,
405 				  enum amdgpu_unmap_queues_action action,
406 				  u64 gpu_addr, u64 seq, uint32_t xcc_id)
407 {
408 	struct mes_unmap_legacy_queue_input queue_input;
409 	int r;
410 
411 	queue_input.xcc_id = xcc_id;
412 	queue_input.action = action;
413 	queue_input.queue_type = ring->funcs->type;
414 	queue_input.doorbell_offset = ring->doorbell_index;
415 	queue_input.pipe_id = ring->pipe;
416 	queue_input.queue_id = ring->queue;
417 	queue_input.trail_fence_addr = gpu_addr;
418 	queue_input.trail_fence_data = seq;
419 
420 	amdgpu_mes_lock(&adev->mes);
421 	r = adev->mes.funcs->unmap_legacy_queue(&adev->mes, &queue_input);
422 	amdgpu_mes_unlock(&adev->mes);
423 	if (r)
424 		dev_err(adev->dev, "failed to unmap legacy queue\n");
425 
426 	return r;
427 }
428 
429 int amdgpu_mes_reset_legacy_queue(struct amdgpu_device *adev,
430 				  struct amdgpu_ring *ring,
431 				  unsigned int vmid,
432 				  bool use_mmio,
433 				  uint32_t xcc_id)
434 {
435 	struct mes_reset_queue_input queue_input;
436 	int r;
437 
438 	memset(&queue_input, 0, sizeof(queue_input));
439 
440 	queue_input.xcc_id = xcc_id;
441 	queue_input.queue_type = ring->funcs->type;
442 	queue_input.doorbell_offset = ring->doorbell_index;
443 	queue_input.me_id = ring->me;
444 	queue_input.pipe_id = ring->pipe;
445 	queue_input.queue_id = ring->queue;
446 	queue_input.mqd_addr = ring->mqd_obj ? amdgpu_bo_gpu_offset(ring->mqd_obj) : 0;
447 	queue_input.wptr_addr = ring->wptr_gpu_addr;
448 	queue_input.vmid = vmid;
449 	queue_input.use_mmio = use_mmio;
450 	queue_input.is_kq = true;
451 	if (ring->funcs->type == AMDGPU_RING_TYPE_GFX)
452 		queue_input.legacy_gfx = true;
453 
454 	amdgpu_mes_lock(&adev->mes);
455 	r = adev->mes.funcs->reset_hw_queue(&adev->mes, &queue_input);
456 	amdgpu_mes_unlock(&adev->mes);
457 	if (r)
458 		dev_err(adev->dev, "failed to reset legacy queue\n");
459 
460 	return r;
461 }
462 
463 int amdgpu_mes_reset_queue_mmio(struct amdgpu_device *adev,
464 				int queue_type,
465 				unsigned int vmid,
466 				unsigned int me,
467 				unsigned int pipe,
468 				unsigned int queue,
469 				uint32_t xcc_id)
470 {
471 	struct mes_reset_queue_input queue_input;
472 	int r;
473 
474 	memset(&queue_input, 0, sizeof(queue_input));
475 
476 	queue_input.xcc_id = xcc_id;
477 	queue_input.me_id = me;
478 	queue_input.pipe_id = pipe;
479 	queue_input.queue_id = queue;
480 	queue_input.vmid = vmid;
481 	queue_input.queue_type = queue_type;
482 	queue_input.use_mmio = true;
483 
484 	amdgpu_mes_lock(&adev->mes);
485 	r = adev->mes.funcs->reset_hw_queue(&adev->mes, &queue_input);
486 	amdgpu_mes_unlock(&adev->mes);
487 	if (r)
488 		dev_err(adev->dev, "failed to reset legacy queue\n");
489 
490 	return r;
491 }
492 
493 int amdgpu_mes_reset_user_queue(struct amdgpu_device *adev,
494 				int queue_type,
495 				unsigned int doorbell_index,
496 				unsigned int xcc_id)
497 {
498 	struct mes_reset_queue_input queue_input;
499 	int r;
500 
501 	memset(&queue_input, 0, sizeof(queue_input));
502 
503 	queue_input.xcc_id = xcc_id;
504 	queue_input.queue_type = queue_type;
505 	queue_input.doorbell_offset = doorbell_index;
506 
507 	amdgpu_mes_lock(&adev->mes);
508 	r = adev->mes.funcs->reset_hw_queue(&adev->mes, &queue_input);
509 	amdgpu_mes_unlock(&adev->mes);
510 	if (r)
511 		dev_err(adev->dev, "failed to reset user queue\n");
512 
513 	return r;
514 }
515 
516 int amdgpu_mes_get_hung_queue_db_array_size(struct amdgpu_device *adev)
517 {
518 	return adev->mes.hung_queue_db_array_size;
519 }
520 
521 int amdgpu_mes_detect_and_reset_hung_queues(struct amdgpu_device *adev,
522 					    int queue_type,
523 					    bool detect_only,
524 					    unsigned int *hung_db_num,
525 					    u32 *hung_db_array,
526 					    uint32_t xcc_id)
527 {
528 	struct mes_detect_and_reset_queue_input input;
529 	u32 *db_array = adev->mes.hung_queue_db_array_cpu_addr[xcc_id];
530 	int hqd_info_offset = adev->mes.hung_queue_hqd_info_offset, r, i;
531 
532 	if (!hung_db_num || !hung_db_array)
533 		return -EINVAL;
534 
535 	if ((queue_type != AMDGPU_RING_TYPE_GFX) &&
536 	    (queue_type != AMDGPU_RING_TYPE_COMPUTE) &&
537 	    (queue_type != AMDGPU_RING_TYPE_SDMA))
538 		return -EINVAL;
539 
540 	/* Clear the doorbell array before detection */
541 	memset(adev->mes.hung_queue_db_array_cpu_addr[xcc_id], AMDGPU_MES_INVALID_DB_OFFSET,
542 		adev->mes.hung_queue_db_array_size * sizeof(u32));
543 	input.queue_type = queue_type;
544 	input.detect_only = detect_only;
545 	input.xcc_id = xcc_id;
546 
547 	r = adev->mes.funcs->detect_and_reset_hung_queues(&adev->mes,
548 							  &input);
549 
550 	if (r && detect_only) {
551 		dev_err(adev->dev, "Failed to detect hung queues\n");
552 		return r;
553 	}
554 
555 	*hung_db_num = 0;
556 	/* MES passes hung queues' doorbell to driver */
557 	for (i = 0; i < adev->mes.hung_queue_hqd_info_offset; i++) {
558 		/* Finding hung queues where db_array[i] is a valid doorbell */
559 		if (db_array[i] != AMDGPU_MES_INVALID_DB_OFFSET) {
560 			hung_db_array[i] = db_array[i];
561 			*hung_db_num += 1;
562 		}
563 	}
564 
565 	if (r && !(*hung_db_num)) {
566 		dev_err(adev->dev, "Failed to detect and reset hung queues\n");
567 		return r;
568 	}
569 
570 	for (i = hqd_info_offset; i < hqd_info_offset + *hung_db_num; i++)
571 		hung_db_array[i] = db_array[i];
572 
573 	return r;
574 }
575 
576 uint32_t amdgpu_mes_rreg(struct amdgpu_device *adev, uint32_t reg,
577 			 uint32_t xcc_id)
578 {
579 	struct mes_misc_op_input op_input;
580 	int r, val = 0;
581 	uint32_t addr_offset = 0;
582 	uint64_t read_val_gpu_addr;
583 	uint32_t *read_val_ptr;
584 
585 	if (amdgpu_wb_get(adev, &addr_offset)) {
586 		dev_err(adev->dev, "critical bug! too many mes readers\n");
587 		goto error;
588 	}
589 	read_val_gpu_addr = adev->wb.gpu_addr + (addr_offset * 4);
590 	read_val_ptr = (uint32_t *)&adev->wb.wb[addr_offset];
591 	op_input.xcc_id = xcc_id;
592 	op_input.op = MES_MISC_OP_READ_REG;
593 	op_input.read_reg.reg_offset = reg;
594 	op_input.read_reg.buffer_addr = read_val_gpu_addr;
595 
596 	if (!adev->mes.funcs->misc_op) {
597 		dev_err(adev->dev, "mes rreg is not supported!\n");
598 		goto error;
599 	}
600 
601 	amdgpu_mes_lock(&adev->mes);
602 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
603 	amdgpu_mes_unlock(&adev->mes);
604 	if (r)
605 		dev_err(adev->dev, "failed to read reg (0x%x)\n", reg);
606 	else
607 		val = *(read_val_ptr);
608 
609 error:
610 	if (addr_offset)
611 		amdgpu_wb_free(adev, addr_offset);
612 	return val;
613 }
614 
615 int amdgpu_mes_wreg(struct amdgpu_device *adev, uint32_t reg,
616 		    uint32_t val, uint32_t xcc_id)
617 {
618 	struct mes_misc_op_input op_input;
619 	int r;
620 
621 	op_input.xcc_id = xcc_id;
622 	op_input.op = MES_MISC_OP_WRITE_REG;
623 	op_input.write_reg.reg_offset = reg;
624 	op_input.write_reg.reg_value = val;
625 
626 	if (!adev->mes.funcs->misc_op) {
627 		dev_err(adev->dev, "mes wreg is not supported!\n");
628 		r = -EINVAL;
629 		goto error;
630 	}
631 
632 	amdgpu_mes_lock(&adev->mes);
633 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
634 	amdgpu_mes_unlock(&adev->mes);
635 	if (r)
636 		dev_err(adev->dev, "failed to write reg (0x%x)\n", reg);
637 
638 error:
639 	return r;
640 }
641 
642 int amdgpu_mes_reg_write_reg_wait(struct amdgpu_device *adev,
643 				  uint32_t reg0, uint32_t reg1,
644 				  uint32_t ref, uint32_t mask,
645 				  uint32_t xcc_id)
646 {
647 	struct mes_misc_op_input op_input;
648 	int r;
649 
650 	op_input.xcc_id = xcc_id;
651 	op_input.op = MES_MISC_OP_WRM_REG_WR_WAIT;
652 	op_input.wrm_reg.reg0 = reg0;
653 	op_input.wrm_reg.reg1 = reg1;
654 	op_input.wrm_reg.ref = ref;
655 	op_input.wrm_reg.mask = mask;
656 
657 	if (!adev->mes.funcs->misc_op) {
658 		dev_err(adev->dev, "mes reg_write_reg_wait is not supported!\n");
659 		r = -EINVAL;
660 		goto error;
661 	}
662 
663 	amdgpu_mes_lock(&adev->mes);
664 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
665 	amdgpu_mes_unlock(&adev->mes);
666 	if (r)
667 		dev_err(adev->dev, "failed to reg_write_reg_wait\n");
668 
669 error:
670 	return r;
671 }
672 
673 int amdgpu_mes_hdp_flush(struct amdgpu_device *adev)
674 {
675 	uint32_t hdp_flush_req_offset, hdp_flush_done_offset;
676 	struct amdgpu_ring *mes_ring;
677 	uint32_t ref_and_mask = 0, reg_mem_engine = 0;
678 
679 	if (!adev->gfx.funcs->get_hdp_flush_mask) {
680 		dev_err(adev->dev, "mes hdp flush is not supported.\n");
681 		return -EINVAL;
682 	}
683 
684 	mes_ring = &adev->mes.ring[0];
685 	hdp_flush_req_offset = adev->nbio.funcs->get_hdp_flush_req_offset(adev);
686 	hdp_flush_done_offset = adev->nbio.funcs->get_hdp_flush_done_offset(adev);
687 
688 	adev->gfx.funcs->get_hdp_flush_mask(mes_ring, &ref_and_mask, &reg_mem_engine);
689 
690 	return amdgpu_mes_reg_write_reg_wait(adev, hdp_flush_req_offset, hdp_flush_done_offset,
691 					     ref_and_mask, ref_and_mask, 0);
692 }
693 
694 int amdgpu_mes_set_shader_debugger(struct amdgpu_device *adev,
695 				uint64_t process_context_addr,
696 				uint32_t spi_gdbg_per_vmid_cntl,
697 				const uint32_t *tcp_watch_cntl,
698 				uint32_t flags,
699 				bool trap_en,
700 				uint32_t xcc_id)
701 {
702 	struct mes_misc_op_input op_input = {0};
703 	int r;
704 
705 	if (!adev->mes.funcs->misc_op) {
706 		dev_err(adev->dev,
707 			"mes set shader debugger is not supported!\n");
708 		return -EINVAL;
709 	}
710 
711 	op_input.xcc_id = xcc_id;
712 	op_input.op = MES_MISC_OP_SET_SHADER_DEBUGGER;
713 	op_input.set_shader_debugger.process_context_addr = process_context_addr;
714 	op_input.set_shader_debugger.flags.u32all = flags;
715 
716 	/* use amdgpu mes_flush_shader_debugger instead */
717 	if (op_input.set_shader_debugger.flags.process_ctx_flush)
718 		return -EINVAL;
719 
720 	op_input.set_shader_debugger.spi_gdbg_per_vmid_cntl = spi_gdbg_per_vmid_cntl;
721 	memcpy(op_input.set_shader_debugger.tcp_watch_cntl, tcp_watch_cntl,
722 			sizeof(op_input.set_shader_debugger.tcp_watch_cntl));
723 
724 	if (((adev->mes.sched_version & AMDGPU_MES_API_VERSION_MASK) >>
725 			AMDGPU_MES_API_VERSION_SHIFT) >= 14)
726 		op_input.set_shader_debugger.trap_en = trap_en;
727 
728 	amdgpu_mes_lock(&adev->mes);
729 
730 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
731 	if (r)
732 		dev_err(adev->dev, "failed to set_shader_debugger\n");
733 
734 	amdgpu_mes_unlock(&adev->mes);
735 
736 	return r;
737 }
738 
739 int amdgpu_mes_flush_shader_debugger(struct amdgpu_device *adev,
740 				     uint64_t process_context_addr,
741 				     uint32_t xcc_id)
742 {
743 	struct mes_misc_op_input op_input = {0};
744 	int r;
745 
746 	if (!adev->mes.funcs->misc_op) {
747 		dev_err(adev->dev,
748 			"mes flush shader debugger is not supported!\n");
749 		return -EINVAL;
750 	}
751 
752 	op_input.xcc_id = xcc_id;
753 	op_input.op = MES_MISC_OP_SET_SHADER_DEBUGGER;
754 	op_input.set_shader_debugger.process_context_addr = process_context_addr;
755 	op_input.set_shader_debugger.flags.process_ctx_flush = true;
756 
757 	amdgpu_mes_lock(&adev->mes);
758 
759 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
760 	if (r)
761 		dev_err(adev->dev, "failed to set_shader_debugger\n");
762 
763 	amdgpu_mes_unlock(&adev->mes);
764 
765 	return r;
766 }
767 
768 uint32_t amdgpu_mes_get_aggregated_doorbell_index(struct amdgpu_device *adev,
769 						   enum amdgpu_mes_priority_level prio)
770 {
771 	return adev->mes.aggregated_doorbells[prio];
772 }
773 
774 int amdgpu_mes_init_microcode(struct amdgpu_device *adev, int pipe)
775 {
776 	const struct mes_firmware_header_v1_0 *mes_hdr;
777 	struct amdgpu_firmware_info *info;
778 	char ucode_prefix[30];
779 	char fw_name[50];
780 	bool need_retry = false;
781 	u32 *ucode_ptr;
782 	int r;
783 
784 	amdgpu_ucode_ip_version_decode(adev, GC_HWIP, ucode_prefix,
785 				       sizeof(ucode_prefix));
786 	if (adev->enable_uni_mes) {
787 		snprintf(fw_name, sizeof(fw_name),
788 			 "amdgpu/%s_uni_mes.bin", ucode_prefix);
789 	} else if (amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0) &&
790 	    amdgpu_ip_version(adev, GC_HWIP, 0) < IP_VERSION(12, 0, 0)) {
791 		snprintf(fw_name, sizeof(fw_name), "amdgpu/%s_mes%s.bin",
792 			 ucode_prefix,
793 			 pipe == AMDGPU_MES_SCHED_PIPE ? "_2" : "1");
794 		need_retry = true;
795 	} else {
796 		snprintf(fw_name, sizeof(fw_name), "amdgpu/%s_mes%s.bin",
797 			 ucode_prefix,
798 			 pipe == AMDGPU_MES_SCHED_PIPE ? "" : "1");
799 	}
800 
801 	r = amdgpu_ucode_request(adev, &adev->mes.fw[pipe], AMDGPU_UCODE_REQUIRED,
802 				 "%s", fw_name);
803 	if (r && need_retry && pipe == AMDGPU_MES_SCHED_PIPE) {
804 		dev_info(adev->dev, "try to fall back to %s_mes.bin\n", ucode_prefix);
805 		r = amdgpu_ucode_request(adev, &adev->mes.fw[pipe],
806 					 AMDGPU_UCODE_REQUIRED,
807 					 "amdgpu/%s_mes.bin", ucode_prefix);
808 	}
809 
810 	if (r)
811 		goto out;
812 
813 	mes_hdr = (const struct mes_firmware_header_v1_0 *)
814 		adev->mes.fw[pipe]->data;
815 	adev->mes.uc_start_addr[pipe] =
816 		le32_to_cpu(mes_hdr->mes_uc_start_addr_lo) |
817 		((uint64_t)(le32_to_cpu(mes_hdr->mes_uc_start_addr_hi)) << 32);
818 	adev->mes.data_start_addr[pipe] =
819 		le32_to_cpu(mes_hdr->mes_data_start_addr_lo) |
820 		((uint64_t)(le32_to_cpu(mes_hdr->mes_data_start_addr_hi)) << 32);
821 	ucode_ptr = (u32 *)(adev->mes.fw[pipe]->data +
822 			  sizeof(union amdgpu_firmware_header));
823 	adev->mes.fw_version[pipe] =
824 		le32_to_cpu(ucode_ptr[24]) & AMDGPU_MES_VERSION_MASK;
825 
826 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
827 		int ucode, ucode_data;
828 
829 		if (pipe == AMDGPU_MES_SCHED_PIPE) {
830 			ucode = AMDGPU_UCODE_ID_CP_MES;
831 			ucode_data = AMDGPU_UCODE_ID_CP_MES_DATA;
832 		} else {
833 			ucode = AMDGPU_UCODE_ID_CP_MES1;
834 			ucode_data = AMDGPU_UCODE_ID_CP_MES1_DATA;
835 		}
836 
837 		info = &adev->firmware.ucode[ucode];
838 		info->ucode_id = ucode;
839 		info->fw = adev->mes.fw[pipe];
840 		adev->firmware.fw_size +=
841 			ALIGN(le32_to_cpu(mes_hdr->mes_ucode_size_bytes),
842 			      PAGE_SIZE);
843 
844 		info = &adev->firmware.ucode[ucode_data];
845 		info->ucode_id = ucode_data;
846 		info->fw = adev->mes.fw[pipe];
847 		adev->firmware.fw_size +=
848 			ALIGN(le32_to_cpu(mes_hdr->mes_ucode_data_size_bytes),
849 			      PAGE_SIZE);
850 	}
851 
852 	return 0;
853 out:
854 	amdgpu_ucode_release(&adev->mes.fw[pipe]);
855 	return r;
856 }
857 
858 void amdgpu_mes_validate_fw_version(struct amdgpu_device *adev)
859 {
860 	u32 fw_from_ucode = adev->mes.fw_version[AMDGPU_MES_SCHED_PIPE];
861 	u32 fw_from_reg = adev->mes.sched_version & AMDGPU_MES_VERSION_MASK;
862 
863 	if (fw_from_ucode != fw_from_reg)
864 		dev_info(adev->dev,
865 			 "MES firmware reports incorrect version in ucode binary (0x%x vs 0x%x)\n",
866 			 fw_from_ucode, fw_from_reg);
867 }
868 
869 
870 bool amdgpu_mes_suspend_resume_all_supported(struct amdgpu_device *adev)
871 {
872 	uint32_t mes_rev = adev->mes.sched_version & AMDGPU_MES_VERSION_MASK;
873 
874 	return ((amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0) &&
875 		 amdgpu_ip_version(adev, GC_HWIP, 0) < IP_VERSION(12, 0, 0) &&
876 		 mes_rev >= 0x63) ||
877 		amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(12, 0, 0));
878 }
879 
880 bool amdgpu_mes_queue_reset_by_mes_supported(struct amdgpu_device *adev)
881 {
882 	u32 ip_maj = IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0));
883 	u32 ip_min = IP_VERSION_MIN(amdgpu_ip_version(adev, GC_HWIP, 0));
884 	u32 mes_sched = adev->mes.sched_version & AMDGPU_MES_VERSION_MASK;
885 
886 	return (ip_maj == 11 && mes_sched >= 0x8c) ||
887 		((ip_maj == 12 && ip_min == 0) && mes_sched >= 0x8d) ||
888 		((ip_maj == 12 && ip_min == 1) && mes_sched >= 0x7b);
889 }
890 
891 /* Fix me -- node_id is used to identify the correct MES instances in the future */
892 static int amdgpu_mes_set_enforce_isolation(struct amdgpu_device *adev,
893 					    uint32_t node_id, bool enable)
894 {
895 	struct mes_misc_op_input op_input = {0};
896 	int r;
897 
898 	op_input.op = MES_MISC_OP_CHANGE_CONFIG;
899 	op_input.change_config.option.limit_single_process = enable ? 1 : 0;
900 
901 	if (!adev->mes.funcs->misc_op) {
902 		dev_err(adev->dev, "mes change config is not supported!\n");
903 		r = -EINVAL;
904 		goto error;
905 	}
906 
907 	amdgpu_mes_lock(&adev->mes);
908 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
909 	amdgpu_mes_unlock(&adev->mes);
910 	if (r)
911 		dev_err(adev->dev, "failed to change_config.\n");
912 
913 error:
914 	return r;
915 }
916 
917 int amdgpu_mes_update_enforce_isolation(struct amdgpu_device *adev)
918 {
919 	int i, r = 0;
920 
921 	if (adev->enable_mes && adev->gfx.enable_cleaner_shader) {
922 		mutex_lock(&adev->enforce_isolation_mutex);
923 		for (i = 0; i < (adev->xcp_mgr ? adev->xcp_mgr->num_xcps : 1); i++) {
924 			if (adev->enforce_isolation[i] == AMDGPU_ENFORCE_ISOLATION_ENABLE)
925 				r |= amdgpu_mes_set_enforce_isolation(adev, i, true);
926 			else
927 				r |= amdgpu_mes_set_enforce_isolation(adev, i, false);
928 		}
929 		mutex_unlock(&adev->enforce_isolation_mutex);
930 	}
931 	return r;
932 }
933 
934 /**
935  * amdgpu_mes_rs64mem_init - initialize RS64 local memory context arrays
936  *
937  * @mes: MES instance
938  *
939  * Returns 0 on success, negative errno on failure.
940  */
941 int amdgpu_mes_rs64mem_init(struct amdgpu_mes *mes)
942 {
943 	struct amdgpu_device *adev = container_of(mes, struct amdgpu_device, mes);
944 	int r;
945 
946 	if (!mes->use_rs64mem)
947 		return 0;
948 
949 	r = amdgpu_bo_create_kernel(adev, PAGE_SIZE, PAGE_SIZE,
950 				    AMDGPU_GEM_DOMAIN_GTT,
951 				    &mes->ctx_array_size_bo,
952 				    &mes->ctx_array_size_gpu_addr,
953 				    (void **)&mes->ctx_array_size_cpu_ptr);
954 	if (r) {
955 		dev_err(adev->dev,
956 			"Failed to allocate ctx array size BO, r=%d\n", r);
957 		return r;
958 	}
959 
960 	memset(mes->ctx_array_size_cpu_ptr, 0, PAGE_SIZE);
961 
962 	return 0;
963 }
964 
965  /**
966   * amdgpu_mes_rs64mem_fini - tear down RS64 local memory management
967   *
968   * @mes: MES instance
969   */
970 void amdgpu_mes_rs64mem_fini(struct amdgpu_mes *mes)
971 {
972 	if (mes->ctx_array_size_bo) {
973 		amdgpu_bo_free_kernel(&mes->ctx_array_size_bo,
974 				      &mes->ctx_array_size_gpu_addr,
975 				      (void **)&mes->ctx_array_size_cpu_ptr);
976 	}
977 	bitmap_free(mes->proc_ctx_bitmap);
978 	bitmap_free(mes->gang_ctx_bitmap);
979 	mes->use_rs64mem = false;
980 }
981 
982 /**
983  * amdgpu_mes_rs64mem_setup_bitmaps - allocate bitmaps after querying MES
984  *
985  * Called after QUERY_SCHEDULER_STATUS returns and MES has written
986  * the array sizes to the GPU buffer. Reads the sizes and allocates
987  * the tracking bitmaps.
988  *
989  * @mes: MES instance
990  *
991  * Returns 0 on success, negative errno on failure.
992  */
993 int amdgpu_mes_rs64mem_setup_bitmaps(struct amdgpu_mes *mes)
994 {
995 	struct amdgpu_device *adev = container_of(mes, struct amdgpu_device, mes);
996 
997 	if (!mes->use_rs64mem || !mes->ctx_array_size_cpu_ptr)
998 		return 0;
999 
1000 	/* Keep the slots live processes and queues hold across MES re-init. */
1001 	if (mes->proc_ctx_bitmap && mes->gang_ctx_bitmap)
1002 		return 0;
1003 
1004 	/*
1005 	 * MES FW wrote the sizes to the GPU buffer:
1006 	 *   ctx_array_size_cpu_ptr[0] = proc_ctx_array_size (N)
1007 	 *   ctx_array_size_cpu_ptr[1] = gang_ctx_array_size (M)
1008 	 */
1009 	mes->proc_ctx_array_size = mes->ctx_array_size_cpu_ptr[0];
1010 	mes->gang_ctx_array_size = mes->ctx_array_size_cpu_ptr[1];
1011 
1012 	/* Sanity check - MES FW typically returns N=50, M=300 */
1013 	if (mes->proc_ctx_array_size == 0 || mes->gang_ctx_array_size == 0) {
1014 		dev_warn(adev->dev,
1015 			 "MES returned zero ctx array sizes (proc=%u, gang=%u), "
1016 			 "disabling RS64 local memory optimization\n",
1017 			 mes->proc_ctx_array_size, mes->gang_ctx_array_size);
1018 		mes->use_rs64mem = false;
1019 		return 0;
1020 	}
1021 
1022 	/* Cap to safety limits */
1023 	if (mes->proc_ctx_array_size > AMDGPU_MES_PROC_CTX_ARRAY_MAX)
1024 		mes->proc_ctx_array_size = AMDGPU_MES_PROC_CTX_ARRAY_MAX;
1025 	if (mes->gang_ctx_array_size > AMDGPU_MES_GANG_CTX_ARRAY_MAX)
1026 		mes->gang_ctx_array_size = AMDGPU_MES_GANG_CTX_ARRAY_MAX;
1027 
1028 	dev_info(adev->dev,
1029 		 "MES RS64 local memory: proc_ctx_array_size:%u, "
1030 		 "gang_ctx_array_size:%u\n",
1031 		 mes->proc_ctx_array_size, mes->gang_ctx_array_size);
1032 
1033 	/* Allocate bitmaps */
1034 	mes->proc_ctx_bitmap = bitmap_zalloc(mes->proc_ctx_array_size,
1035 					     GFP_KERNEL);
1036 	if (!mes->proc_ctx_bitmap) {
1037 		mes->use_rs64mem = false;
1038 		return -ENOMEM;
1039 	}
1040 
1041 	mes->gang_ctx_bitmap = bitmap_zalloc(mes->gang_ctx_array_size,
1042 					     GFP_KERNEL);
1043 	if (!mes->gang_ctx_bitmap) {
1044 		bitmap_free(mes->proc_ctx_bitmap);
1045 		mes->proc_ctx_bitmap = NULL;
1046 		mes->use_rs64mem = false;
1047 		return -ENOMEM;
1048 	}
1049 
1050 	return 0;
1051 }
1052 
1053 /**
1054  * amdgpu_mes_alloc_proc_ctx_index - allocate a process context slot
1055  *
1056  * @mes: MES instance
1057  * @index: the allocated process context index
1058  *
1059  * Returns 0 on success, -ENOSPC if all slots are used, or
1060  * -EOPNOTSUPP if RS64 local memory is unavailable.
1061  */
1062 int amdgpu_mes_alloc_proc_ctx_index(struct amdgpu_mes *mes,
1063 				    uint32_t *index)
1064 {
1065 	unsigned long bit;
1066 
1067 	if (!mes->use_rs64mem || !mes->proc_ctx_bitmap)
1068 		return -EOPNOTSUPP;
1069 
1070 	amdgpu_mes_lock(mes);
1071 	bit = find_first_zero_bit(mes->proc_ctx_bitmap,
1072 				  mes->proc_ctx_array_size);
1073 	if (bit >= mes->proc_ctx_array_size) {
1074 		amdgpu_mes_unlock(mes);
1075 		return -ENOSPC;
1076 	}
1077 	set_bit(bit, mes->proc_ctx_bitmap);
1078 	*index = (uint32_t)bit;
1079 	amdgpu_mes_unlock(mes);
1080 
1081 	return 0;
1082 }
1083 
1084  /**
1085   * amdgpu_mes_free_proc_ctx_index - free a process context slot
1086   *
1087   * @mes: MES instance
1088   * @index: process context index is released
1089   */
1090 void amdgpu_mes_free_proc_ctx_index(struct amdgpu_mes *mes,
1091 				    uint32_t index)
1092 {
1093 	if (!mes->use_rs64mem || !mes->proc_ctx_bitmap)
1094 		return;
1095 	if (index >= mes->proc_ctx_array_size)
1096 		return;
1097 
1098 	amdgpu_mes_lock(mes);
1099 	clear_bit(index, mes->proc_ctx_bitmap);
1100 	amdgpu_mes_unlock(mes);
1101 }
1102 
1103  /**
1104   * amdgpu_mes_alloc_gang_ctx_index - allocate a gang context slot
1105   *
1106   * @mes: MES instance
1107   * @index: the allocated gang context index
1108   *
1109   * Returns 0 on success, -ENOSPC if all slots are used, or
1110   * -EOPNOTSUPP if RS64 local memory is unavailable.
1111   */
1112 int amdgpu_mes_alloc_gang_ctx_index(struct amdgpu_mes *mes,
1113 				    uint32_t *index)
1114 {
1115 	unsigned long bit;
1116 
1117 	if (!mes->use_rs64mem || !mes->gang_ctx_bitmap)
1118 		return -EOPNOTSUPP;
1119 
1120 	amdgpu_mes_lock(mes);
1121 	bit = find_first_zero_bit(mes->gang_ctx_bitmap,
1122 				  mes->gang_ctx_array_size);
1123 	if (bit >= mes->gang_ctx_array_size) {
1124 		amdgpu_mes_unlock(mes);
1125 		return -ENOSPC;
1126 	}
1127 	set_bit(bit, mes->gang_ctx_bitmap);
1128 	*index = bit;
1129 	amdgpu_mes_unlock(mes);
1130 
1131 	return 0;
1132 }
1133 
1134  /**
1135   * amdgpu_mes_free_gang_ctx_index - free a gang context slot
1136   *
1137   * @mes: MES instance
1138   * @index: gang context index is released
1139   */
1140 void amdgpu_mes_free_gang_ctx_index(struct amdgpu_mes *mes,
1141 				    uint32_t index)
1142 {
1143 	if (!mes->use_rs64mem || !mes->gang_ctx_bitmap)
1144 		return;
1145 	if (index >= mes->gang_ctx_array_size)
1146 		return;
1147 
1148 	amdgpu_mes_lock(mes);
1149 	clear_bit(index, mes->gang_ctx_bitmap);
1150 	amdgpu_mes_unlock(mes);
1151 }
1152 
1153 int amdgpu_mes_notify_unmap_queue(struct amdgpu_device *adev)
1154 {
1155 	struct mes_misc_op_input op_input = {0};
1156 	int r;
1157 
1158 	op_input.op = MES_MISC_OP_NOTIFY_WORK_ON_UNMAPPED_QUEUE;
1159 
1160 	if (!adev->mes.funcs->misc_op) {
1161 		dev_err(adev->dev, "mes notify unmap queue is not supported!\n");
1162 		r = -EINVAL;
1163 		goto error;
1164 	}
1165 
1166 	amdgpu_mes_lock(&adev->mes);
1167 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
1168 	amdgpu_mes_unlock(&adev->mes);
1169 	if (r)
1170 		dev_err(adev->dev, "failed to notify unmap queue.\n");
1171 
1172 error:
1173 	return r;
1174 }
1175 
1176 /* Interval for notifying MES of work on unmapped queues during oversubscription */
1177 #define AMDGPU_USERQ_UNMAP_NOTIFY_DELAY_US 50
1178 
1179 static unsigned int amdgpu_mes_userq_hw_queue_num(struct amdgpu_device *adev)
1180 {
1181 	int num_xcc = adev->gfx.xcc_mask ? NUM_XCC(adev->gfx.xcc_mask) : 1;
1182 	unsigned int n = bitmap_weight(adev->gfx.me.queue_bitmap, AMDGPU_MAX_GFX_QUEUES);
1183 	int i;
1184 
1185 	for (i = 0; i < num_xcc; i++)
1186 		n += bitmap_weight(adev->gfx.mec_bitmap[i].queue_bitmap,
1187 				    AMDGPU_MAX_COMPUTE_QUEUES);
1188 
1189 	return n;
1190 }
1191 
1192 static void amdgpu_mes_userq_notify_unmap_work_handler(struct work_struct *work)
1193 {
1194 	struct amdgpu_mes *mes = container_of(work, struct amdgpu_mes,
1195 					       userq_notify_unmap_work.work);
1196 	struct amdgpu_device *adev = mes->adev;
1197 
1198 	/* MES is unusable during GPU recovery; the re-arm below retries later */
1199 	if (down_read_trylock(&adev->reset_domain->sem)) {
1200 		amdgpu_mes_notify_unmap_queue(adev);
1201 		up_read(&adev->reset_domain->sem);
1202 	}
1203 
1204 	/* Re-arm if still oversubscribed */
1205 	if (atomic_read(&mes->userq_hw_queue_count) >
1206 	    amdgpu_mes_userq_hw_queue_num(adev))
1207 		queue_delayed_work(system_wq, &mes->userq_notify_unmap_work,
1208 				   usecs_to_jiffies(AMDGPU_USERQ_UNMAP_NOTIFY_DELAY_US));
1209 }
1210 
1211 /*
1212  * Called after a GFX11 usermode queue is successfully mapped to MES.
1213  * Starts the periodic unmap-notify timer if this pushed the device into
1214  * HW queue oversubscription.
1215  */
1216 void amdgpu_mes_userq_queue_mapped(struct amdgpu_device *adev)
1217 {
1218 	if (amdgpu_sriov_vf(adev))
1219 		return;
1220 
1221 	if (!(amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0) &&
1222 	      amdgpu_ip_version(adev, GC_HWIP, 0) < IP_VERSION(12, 0, 0)))
1223 		return;
1224 
1225 	if (atomic_inc_return(&adev->mes.userq_hw_queue_count) >
1226 	    amdgpu_mes_userq_hw_queue_num(adev))
1227 		queue_delayed_work(system_wq, &adev->mes.userq_notify_unmap_work,
1228 				   usecs_to_jiffies(AMDGPU_USERQ_UNMAP_NOTIFY_DELAY_US));
1229 }
1230 
1231 /*
1232  * Called after a GFX11 usermode queue is unmapped from MES. Stops the
1233  * periodic unmap-notify timer once oversubscription clears.
1234  */
1235 void amdgpu_mes_userq_queue_unmapped(struct amdgpu_device *adev)
1236 {
1237 	if (amdgpu_sriov_vf(adev))
1238 		return;
1239 
1240 	if (!(amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(11, 0, 0) &&
1241 	      amdgpu_ip_version(adev, GC_HWIP, 0) < IP_VERSION(12, 0, 0)))
1242 		return;
1243 
1244 	if (atomic_dec_return(&adev->mes.userq_hw_queue_count) <=
1245 	    amdgpu_mes_userq_hw_queue_num(adev))
1246 		cancel_delayed_work(&adev->mes.userq_notify_unmap_work);
1247 }
1248 
1249 /*
1250  * MES firmware debug extension ("mes_dbgext")
1251  *
1252  * The driver hands the MES a log buffer; the MES firmware writes text log items
1253  * into it and the driver drains and prints them.  The buffer is a single
1254  * circular byte stream with a 16-byte header at offset 0:
1255  *
1256  *   dword0 : rptr        - driver reads/advances (with wrap)
1257  *   dword1 : wptr        - firmware writes/advances (with wrap)
1258  *   dword2 : buffer_size - total buffer size in bytes (set by the driver)
1259  *   dword3 : header_size - size of this header / wrap-back offset (16)
1260  *
1261  * Item data starts at header_size and wraps from buffer_size back to
1262  * header_size.  Each log item begins with a 4-byte header (type, xor-signature,
1263  * 16-bit length including the header) followed by NUL-free text.
1264  *
1265  * The driver owns rptr; the firmware owns wptr.  The collection method is
1266  * selectable via the mes_dbgext_options bit0: interrupt-driven (default - the
1267  * FW raises its host interrupt per message, handled via the CP EOP path) or a
1268  * polling kthread.  Polling is also used automatically as a fallback when the
1269  * ASIC has no IRQ-enable hook.
1270  *
1271  * NOTE: this requires an MES firmware image built with debug-extension support.
1272  */
1273 
1274 #define MES_DBGEXT_MAX_ITEM_SIZE	2048
1275 #define MES_DBGEXT_POLL_INTERVAL_MS	200
1276 /* Default log-buffer size (KB) used when enabled at runtime with no size set. */
1277 #define MES_DBGEXT_DEFAULT_KB		8
1278 
1279 /* Log item text record types (must match mes_aux LOG__* in mes_dbgext.cpp). */
1280 #define MES_DBGEXT_MSG			0x80
1281 #define MES_DBGEXT_MSG_ASSERT		0x81
1282 #define MES_DBGEXT_MSG_HALT		0x82
1283 
1284 /*
1285  * Log buffer option bits, must match the MES firmware's MES_DBGEXT_INIT_DATA.
1286  * bit0 = trigger_interrupt_per_new_msg: when SET, the firmware raises the
1287  * debug-message host interrupt after each message
1288  * (mes_dbgext.cpp: "if (trigger_interrupt_per_new_msg) SendIntToHost()").
1289  * When CLEAR, the firmware only writes the buffer and the driver must poll.
1290  */
1291 #define MES_DBGEXT_OPT_TRIGGER_INT_PER_MSG	(1ULL << 0)
1292 
1293 /*
1294  * MES firmware routes mes_dbgext through the shared "mes_aux" component, which
1295  * uses a zone-partitioned buffer layout:
1296  *
1297  *   offset 0: struct { u32 zone_count; struct {u32 offset, length}[zone_count]; }
1298  *
1299  * Each zone starts (at its byte offset from the buffer base) with a 16-byte
1300  * LOG_ZONE_HEADER {rptr, wptr, buffer_size, header_size} whose rptr/wptr are
1301  * relative to the zone start and wrap from buffer_size back to header_size.
1302  * Every log item begins with an 8-byte header: type, xor-signature, a 24-bit
1303  * big-endian length (total item size including the header, in bytes[2..4]),
1304  * then level, seq and a reserved byte.  Zone 0 carries human-readable text
1305  * (printed to dmesg); other zones carry binary event/interrupt/api records
1306  * (types 0x93..0x95) that are not text and are skipped.
1307  *
1308  * The driver seeds only the total buffer size in the first dword; the firmware
1309  * (mes_aux InitializeLogBuffer) reads it and writes the zone header in place.
1310  */
1311 #define MES_DBGEXT_ITEM_HDR_SIZE	8
1312 #define MES_DBGEXT_MAX_ZONES		8
1313 
1314 /*
1315  * mes_aux option word (struct MesExtConfig) layout, which differs from the
1316  * gfx11 MES_DBGEXT_INIT_DATA: bit0 is host_poll_msg (INVERTED sense - when set,
1317  * the firmware does not raise the per-message interrupt), bit1 enables logging,
1318  * and bit3 enables an internal write-back cache (left off for prompt delivery).
1319  */
1320 #define MES_DBGEXT_AUX_OPT_HOST_POLL		(1ULL << 0)
1321 #define MES_DBGEXT_AUX_OPT_ENABLE_MES_LOG	(1ULL << 1)
1322 #define MES_DBGEXT_AUX_OPT_ENABLE_LOG_CACHE	(1ULL << 3)
1323 
1324 struct mes_dbgext_zone_info {
1325 	u32 offset;
1326 	u32 length;
1327 };
1328 
1329 struct mes_dbgext_zone_header {
1330 	u32 rptr;
1331 	u32 wptr;
1332 	u32 buffer_size;
1333 	u32 header_size;
1334 };
1335 
1336 /*
1337  * Copy @n bytes out of the circular data region starting at byte offset @off,
1338  * wrapping back to @hdr_size when @buffer_size is reached.
1339  */
1340 static void mes_dbgext_buf_read(const u8 *buf, u32 buffer_size, u32 hdr_size,
1341 				u32 off, u8 *dst, u32 n)
1342 {
1343 	while (n--) {
1344 		*dst++ = buf[off++];
1345 		if (off >= buffer_size)
1346 			off = hdr_size;
1347 	}
1348 }
1349 
1350 static void mes_dbgext_print_item(struct amdgpu_device *adev, int xcc,
1351 				  u32 type, char *text)
1352 {
1353 	size_t n = strlen(text);
1354 	char pfx[12] = "";
1355 
1356 	/* Normalize to exactly one trailing newline: the gfx11 firmware appends
1357 	 * one to the text, the gfx12/mes_aux firmware does not.
1358 	 */
1359 	while (n && (text[n - 1] == '\n' || text[n - 1] == '\r'))
1360 		text[--n] = '\0';
1361 
1362 	/* Tag with the source XCC only when more than one is being logged, so
1363 	 * single-XCC (gfx11/gfx12) output is unchanged.
1364 	 */
1365 	if (adev->mes.dbgext_num_xcc > 1)
1366 		snprintf(pfx, sizeof(pfx), " xcc%d", xcc);
1367 
1368 	switch (type) {
1369 	case MES_DBGEXT_MSG_ASSERT:
1370 		dev_err(adev->dev, "[mes_dbgext%s] ASSERT %s\n", pfx, text);
1371 		break;
1372 	case MES_DBGEXT_MSG:
1373 		dev_info(adev->dev, "[mes_dbgext%s] %s\n", pfx, text);
1374 		break;
1375 	default:
1376 		dev_warn(adev->dev, "[mes_dbgext%s] %s\n", pfx, text);
1377 		break;
1378 	}
1379 }
1380 
1381 /*
1382  * Drain a single zone of the mes_aux buffer.  @zbase points at the
1383  * zone start (its LOG_ZONE_HEADER); rptr/wptr are relative to @zbase.  @item is
1384  * caller-provided scratch of at least MES_DBGEXT_MAX_ITEM_SIZE + 1 bytes.
1385  */
1386 static void mes_dbgext_process_zone(struct amdgpu_device *adev, u8 *zbase,
1387 				    u8 *item, int xcc)
1388 {
1389 	struct mes_dbgext_zone_header *zh =
1390 		(struct mes_dbgext_zone_header *)zbase;
1391 	u32 rptr, wptr, buffer_size, hdr_size;
1392 
1393 	buffer_size = READ_ONCE(zh->buffer_size);
1394 	hdr_size = READ_ONCE(zh->header_size);
1395 	rptr = READ_ONCE(zh->rptr);
1396 	wptr = READ_ONCE(zh->wptr);
1397 
1398 	/* Nothing to do until the firmware has written a new message. */
1399 	if (rptr == wptr)
1400 		return;
1401 
1402 	/*
1403 	 * Order the wptr load ahead of the item-body loads below.  The firmware
1404 	 * publishes an item by writing its body first and advancing wptr last;
1405 	 * this barrier ensures we observe the body that wptr claims is present.
1406 	 */
1407 	dma_rmb();
1408 
1409 	if (hdr_size < sizeof(*zh) || buffer_size <= hdr_size ||
1410 	    rptr < hdr_size || rptr >= buffer_size ||
1411 	    wptr < hdr_size || wptr >= buffer_size)
1412 		return;
1413 
1414 	while (rptr != wptr) {
1415 		u8 hb[MES_DBGEXT_ITEM_HDR_SIZE];
1416 		u32 type, len;
1417 
1418 		mes_dbgext_buf_read(zbase, buffer_size, hdr_size, rptr,
1419 				    hb, sizeof(hb));
1420 		type = hb[0];
1421 		len = ((u32)hb[2] << 16) | ((u32)hb[3] << 8) | hb[4];
1422 
1423 		/* sign = xor of all header bytes except the sign byte itself. */
1424 		if ((u8)(hb[0] ^ hb[2] ^ hb[3] ^ hb[4] ^ hb[5] ^ hb[6]) != hb[1] ||
1425 		    len <= MES_DBGEXT_ITEM_HDR_SIZE ||
1426 		    len > MES_DBGEXT_MAX_ITEM_SIZE ||
1427 		    len > buffer_size - hdr_size) {
1428 			dev_dbg(adev->dev,
1429 				"mes_dbgext: bad item @%u (type 0x%x len %u), skipping to %u\n",
1430 				rptr, type, len, wptr);
1431 			rptr = wptr;
1432 			break;
1433 		}
1434 
1435 		/*
1436 		 * Zones also carry binary event/interrupt/api records (types
1437 		 * 0x93..0x95) whose payload is a NUL-terminated file name
1438 		 * followed by raw struct bytes - not human-readable text.  Only
1439 		 * print the text record types (MSG/ASSERT/HALT); consume and
1440 		 * skip everything else so the binary records' file-name prefix
1441 		 * is not dumped to dmesg.
1442 		 */
1443 		if (type == MES_DBGEXT_MSG ||
1444 		    type == MES_DBGEXT_MSG_ASSERT ||
1445 		    type == MES_DBGEXT_MSG_HALT) {
1446 			mes_dbgext_buf_read(zbase, buffer_size, hdr_size, rptr,
1447 					    item, len);
1448 			item[len] = '\0';
1449 			mes_dbgext_print_item(adev, xcc, type,
1450 				(char *)item + MES_DBGEXT_ITEM_HDR_SIZE);
1451 		}
1452 
1453 		rptr += len;
1454 		if (rptr >= buffer_size)
1455 			rptr -= (buffer_size - hdr_size);
1456 		if (rptr < hdr_size || rptr >= buffer_size) {
1457 			rptr = wptr;
1458 			break;
1459 		}
1460 	}
1461 
1462 	/*
1463 	 * Ensure all item-body reads complete before we publish the new rptr;
1464 	 * otherwise the firmware may observe the advanced rptr and reuse buffer
1465 	 * space we have not finished reading.
1466 	 */
1467 	dma_wmb();
1468 	WRITE_ONCE(zh->rptr, rptr);
1469 }
1470 
1471 /*
1472  * Drain one per-XCC region: parse its zone table (a zone_count dword followed
1473  * by per-zone {offset,length} descriptors) and drain each zone.  @base points
1474  * at the region start; @xcc tags the output.
1475  */
1476 static void mes_dbgext_process_region(struct amdgpu_device *adev, u8 *base, int xcc)
1477 {
1478 	struct amdgpu_mes *mes = &adev->mes;
1479 	u32 zone_count, hdr_len, z;
1480 	u8 *item;
1481 
1482 	if (!base)
1483 		return;
1484 
1485 	zone_count = READ_ONCE(*(u32 *)base);
1486 	if (zone_count == 0 || zone_count > MES_DBGEXT_MAX_ZONES)
1487 		return;
1488 
1489 	hdr_len = sizeof(u32) + zone_count * sizeof(struct mes_dbgext_zone_info);
1490 	if (hdr_len >= mes->dbgext_log_size)
1491 		return;
1492 
1493 	/* Scratch to linearize a (possibly wrapped) item; +1 for NUL. */
1494 	item = kmalloc(MES_DBGEXT_MAX_ITEM_SIZE + 1, GFP_KERNEL);
1495 	if (!item)
1496 		return;
1497 
1498 	for (z = 0; z < zone_count; z++) {
1499 		struct mes_dbgext_zone_info *zi =
1500 			(struct mes_dbgext_zone_info *)(base + sizeof(u32)) + z;
1501 		u32 zoff = READ_ONCE(zi->offset);
1502 		u32 zlen = READ_ONCE(zi->length);
1503 
1504 		/* Skip a bogus zone descriptor rather than the whole buffer. */
1505 		if (zoff < hdr_len || zoff > mes->dbgext_log_size ||
1506 		    zlen < sizeof(struct mes_dbgext_zone_header) ||
1507 		    zlen > mes->dbgext_log_size - zoff)
1508 			continue;
1509 
1510 		mes_dbgext_process_zone(adev, base + zoff, item, xcc);
1511 	}
1512 
1513 	kfree(item);
1514 }
1515 
1516 static void mes_dbgext_process_all(struct amdgpu_device *adev)
1517 {
1518 	struct amdgpu_mes *mes = &adev->mes;
1519 	u32 num_xcc = mes->dbgext_num_xcc ? mes->dbgext_num_xcc : 1;
1520 	u8 *buf = mes->dbgext_log_cpu_addr;
1521 	u32 xcc;
1522 
1523 	if (!buf)
1524 		return;
1525 
1526 	/*
1527 	 * The buffer holds num_xcc back-to-back per-XCC regions, each
1528 	 * dbgext_log_size bytes.  Drain each region and tag its output with the
1529 	 * source XCC (single-XCC ASICs have exactly one region).
1530 	 */
1531 	for (xcc = 0; xcc < num_xcc; xcc++) {
1532 		u8 *base = buf + xcc * mes->dbgext_log_size;
1533 
1534 		mes_dbgext_process_region(adev, base, xcc);
1535 	}
1536 }
1537 
1538 static int amdgpu_mes_dbgext_reader(void *param)
1539 {
1540 	struct amdgpu_device *adev = param;
1541 
1542 	while (!kthread_should_stop()) {
1543 		mes_dbgext_process_all(adev);
1544 		msleep_interruptible(MES_DBGEXT_POLL_INTERVAL_MS);
1545 	}
1546 	return 0;
1547 }
1548 
1549 /* Runs in process context; does the (sleepable) buffer drain. */
1550 static void amdgpu_mes_dbgext_work_fn(struct work_struct *work)
1551 {
1552 	struct amdgpu_mes *mes = container_of(work, struct amdgpu_mes,
1553 					      dbgext_work);
1554 	struct amdgpu_device *adev =
1555 		container_of(mes, struct amdgpu_device, mes);
1556 
1557 	mes_dbgext_process_all(adev);
1558 }
1559 
1560 /*
1561  * Called from the MES interrupt handler (hard/soft IRQ context).  Decodes the
1562  * MES->host interrupt type and, for a debug-message notification, schedules the
1563  * drain on a workqueue (the parser sleeps / allocates, so it cannot run here).
1564  */
1565 void amdgpu_mes_dbgext_notify(struct amdgpu_device *adev, u32 context_data)
1566 {
1567 	struct amdgpu_mes *mes = &adev->mes;
1568 
1569 	/*
1570 	 * Caller has already matched MES_DBGMSG (type 7 in bits 31:26 of the
1571 	 * IH context dword).  Kick the drain; it is a no-op when the log has
1572 	 * no new data.
1573 	 */
1574 
1575 	/*
1576 	 * Only the interrupt path may schedule the drain work.  In polling mode
1577 	 * the kthread owns rptr; honoring a stale/spurious interrupt here would
1578 	 * let the work item and the kthread drain concurrently and race on rptr.
1579 	 */
1580 	if (!READ_ONCE(mes->dbgext_use_irq))
1581 		return;
1582 
1583 	if (READ_ONCE(mes->dbgext_log_cpu_addr))
1584 		schedule_work(&mes->dbgext_work);
1585 }
1586 
1587 static int amdgpu_mes_dbgext_setup_fw(struct amdgpu_device *adev, u32 xcc_id,
1588 				      u64 log_buffer_mc_addr, u64 log_options)
1589 {
1590 	struct amdgpu_mes *mes = &adev->mes;
1591 	struct mes_misc_op_input op_input = {0};
1592 	int r;
1593 
1594 	if (!mes->funcs || !mes->funcs->misc_op)
1595 		return -EINVAL;
1596 
1597 	op_input.xcc_id = xcc_id;
1598 	op_input.op = MES_MISC_OP_SETUP_MES_DBGEXT;
1599 	op_input.setup_mes_dbgext.log_buffer_mc_addr = log_buffer_mc_addr;
1600 	op_input.setup_mes_dbgext.log_options = log_options;
1601 
1602 	amdgpu_mes_lock(mes);
1603 	r = mes->funcs->misc_op(mes, &op_input);
1604 	amdgpu_mes_unlock(mes);
1605 
1606 	return r;
1607 }
1608 
1609 static int amdgpu_mes_dbgext_start_locked(struct amdgpu_device *adev)
1610 {
1611 	struct amdgpu_mes *mes = &adev->mes;
1612 	struct task_struct *reader;
1613 	bool use_irq;
1614 	u64 fw_options;
1615 	u32 size;
1616 	u32 req_kb;
1617 	u32 num_xcc, xcc;
1618 	int r;
1619 
1620 	/*
1621 	 * Effective buffer size (KB): the module parameter wins (so a boot-time
1622 	 * request is honored), otherwise use the runtime-requested size set by
1623 	 * the debugfs on/off switch.  Zero means the feature is off.
1624 	 */
1625 	req_kb = amdgpu_mes_dbgext_buffer_size ?
1626 		 amdgpu_mes_dbgext_buffer_size : mes->dbgext_runtime_kb;
1627 	if (!req_kb)
1628 		return 0;
1629 
1630 	/*
1631 	 * Already armed for this hw bring-up.  hw_init() can run start() more
1632 	 * than once (e.g. kiq_hw_init() -> hw_init(), then the MES IP block's
1633 	 * own hw_init()); only the first should arm.  A post-suspend resume
1634 	 * comes back here with the buffer kept but dbgext_active cleared by
1635 	 * stop(), so re-arm runs below.
1636 	 */
1637 
1638 	if (mes->dbgext_active)
1639 		return 0;
1640 
1641 	if (!mes->funcs || !mes->funcs->misc_op) {
1642 		dev_warn(adev->dev, "mes_dbgext not supported by this MES\n");
1643 		return 0;
1644 	}
1645 
1646 	/*
1647 	 * Log every XCC's MES firmware.  Each XCC runs its own MES and gets its
1648 	 * own per-XCC region within one buffer (see dbgext_num_xcc); single-XCC
1649 	 * ASICs (gfx11/gfx12) collapse to a single region.
1650 	 */
1651 	num_xcc = adev->gfx.xcc_mask ? NUM_XCC(adev->gfx.xcc_mask) : 1;
1652 	mes->dbgext_num_xcc = num_xcc;
1653 
1654 	if (!mes->dbgext_log_gpu_obj) {
1655 		/* Clamp to a sane range (4 KB .. 1 MB), per XCC. */
1656 		size = clamp(req_kb, 4U, 1024U);
1657 		size = ALIGN((u32)size * SZ_1K, PAGE_SIZE);
1658 		/*
1659 		 * The mes_aux firmware splits the buffer into per-thread zones
1660 		 * and rejects buffers that are not larger than its 4 KB minimum,
1661 		 * so give it at least 8 KB.
1662 		 */
1663 		if (size < SZ_8K)
1664 			size = SZ_8K;
1665 
1666 		/* One buffer holds num_xcc back-to-back per-XCC regions. */
1667 		r = amdgpu_bo_create_kernel(adev, size * num_xcc, PAGE_SIZE,
1668 					    AMDGPU_GEM_DOMAIN_GTT,
1669 					    &mes->dbgext_log_gpu_obj,
1670 					    &mes->dbgext_log_gpu_addr,
1671 					    &mes->dbgext_log_cpu_addr);
1672 		if (r) {
1673 			dev_warn(adev->dev,
1674 				 "failed to create mes_dbgext log buffer (%d)\n", r);
1675 			return r;
1676 		}
1677 		mes->dbgext_log_size = size;
1678 		INIT_WORK(&mes->dbgext_work, amdgpu_mes_dbgext_work_fn);
1679 	} else {
1680 		/*
1681 		 * Resume: the log buffer is kept allocated across a suspend/
1682 		 * resume cycle (freeing a kernel BO while suspended is not
1683 		 * allowed), so reuse it and just re-arm the firmware below.
1684 		 */
1685 		size = mes->dbgext_log_size;
1686 	}
1687 
1688 	/*
1689 	 * (Re)initialize each per-XCC region's header.  On resume the MES was
1690 	 * reset and re-lays its header, and the driver's rptr/wptr must restart
1691 	 * clean.  Clear the whole buffer once, then seed every region.
1692 	 */
1693 	memset(mes->dbgext_log_cpu_addr, 0, size * num_xcc);
1694 	for (xcc = 0; xcc < num_xcc; xcc++) {
1695 		u8 *base = (u8 *)mes->dbgext_log_cpu_addr + xcc * size;
1696 
1697 		/*
1698 		 * mes_aux: seed only the total region size in the first dword.
1699 		 * The firmware (InitializeLogBuffer) reads it during setup and
1700 		 * lays out its own zone-partitioned header in place.
1701 		 */
1702 		*(u32 *)base = size;
1703 	}
1704 
1705 	/*
1706 	 * The options word is passed verbatim to the firmware.  bit0
1707 	 * (trigger_interrupt_per_new_msg) selects the collection method:
1708 	 *   set   -> firmware raises an interrupt per message; the driver
1709 	 *            collects them via the CP EOP path (gfx_v11_0_eop_irq).
1710 	 *   clear -> firmware only writes the buffer; the driver polls with a
1711 	 *            kthread.
1712 	 * If interrupts are requested but the ASIC has no CP enable hook, fall
1713 	 * back to polling and clear the bit so the firmware does not raise an
1714 	 * interrupt nobody will service.
1715 	 */
1716 	mes->dbgext_log_options = (u32)amdgpu_mes_dbgext_options;
1717 	use_irq = (mes->dbgext_log_options & MES_DBGEXT_OPT_TRIGGER_INT_PER_MSG) &&
1718 		  mes->funcs->enable_dbgext_irq;
1719 	if (!use_irq)
1720 		mes->dbgext_log_options &= ~MES_DBGEXT_OPT_TRIGGER_INT_PER_MSG;
1721 	mes->dbgext_use_irq = use_irq;
1722 
1723 	/*
1724 	 * Translate the options to the mes_aux firmware layout: enable logging
1725 	 * (bit1), select interrupt vs polling via host_poll_msg (bit0, inverted
1726 	 * sense), and leave the write-back cache off for prompt delivery.
1727 	 */
1728 	fw_options = MES_DBGEXT_AUX_OPT_ENABLE_MES_LOG;
1729 	if (!use_irq)
1730 		fw_options |= MES_DBGEXT_AUX_OPT_HOST_POLL;
1731 
1732 	/*
1733 	 * Mark the feature active *before* arming the firmware.  setup_fw()
1734 	 * below makes the firmware emit its first ("enabled") message and, in
1735 	 * interrupt mode, immediately raise the host interrupt for it.  The EOP
1736 	 * handler drops the drain unless dbgext_active is already set, so if it
1737 	 * were set only after setup_fw() the enable interrupt would race the
1738 	 * handler and be lost - and on emulation no further message/interrupt
1739 	 * follows to recover it.  Cleared again on the error paths below.
1740 	 */
1741 	mes->dbgext_active = true;
1742 
1743 	/* Enable delivery of the MES host interrupt at the CP (process ctx). */
1744 	if (use_irq)
1745 		mes->funcs->enable_dbgext_irq(mes, true);
1746 
1747 	/* Point each XCC's MES firmware at its own per-XCC region. */
1748 	for (xcc = 0; xcc < num_xcc; xcc++) {
1749 		r = amdgpu_mes_dbgext_setup_fw(adev, xcc,
1750 					       mes->dbgext_log_gpu_addr + xcc * size,
1751 					       fw_options);
1752 		if (r) {
1753 			dev_err(adev->dev,
1754 				"failed to setup mes_dbgext in FW on xcc%u (%d)\n",
1755 				xcc, r);
1756 			/* Detach the XCCs already armed before bailing. */
1757 			while (xcc--)
1758 				amdgpu_mes_dbgext_setup_fw(adev, xcc, 0, 0);
1759 			goto err_disable;
1760 		}
1761 	}
1762 
1763 	if (!use_irq) {
1764 		/*
1765 		 * Never leak a reader: if one is somehow still around (a missed
1766 		 * stop()), reap it before creating a new one so it cannot outlive
1767 		 * the module.
1768 		 */
1769 		if (WARN_ON(mes->dbgext_reader)) {
1770 			kthread_stop(mes->dbgext_reader);
1771 			mes->dbgext_reader = NULL;
1772 		}
1773 
1774 		reader = kthread_run(amdgpu_mes_dbgext_reader, adev,
1775 				     "amdgpu_mes_dbgext");
1776 		if (IS_ERR(reader)) {
1777 			r = PTR_ERR(reader);
1778 			dev_err(adev->dev,
1779 				"failed to start mes_dbgext reader (%d)\n", r);
1780 			goto err_fw_detach;
1781 		}
1782 		mes->dbgext_reader = reader;
1783 	}
1784 
1785 	dev_info(adev->dev,
1786 		 "mes_dbgext enabled: %u KB x %u xcc @ 0x%llx (%s, fw options 0x%llx)\n",
1787 		 size / SZ_1K, num_xcc, mes->dbgext_log_gpu_addr,
1788 		 use_irq ? "interrupt" : "polling", fw_options);
1789 
1790 	/*
1791 	 * In interrupt mode the firmware has already written its "enabled"
1792 	 * message (and raised the one-shot enable interrupt) during setup_fw()
1793 	 * above.  Kick an explicit drain now so that message is collected even
1794 	 * if that interrupt was missed, and so the log is not left waiting for
1795 	 * the next firmware message - which, on emulation, may never come.
1796 	 */
1797 	if (use_irq)
1798 		amdgpu_mes_dbgext_notify(adev, 0);
1799 
1800 	return 0;
1801 
1802 err_fw_detach:
1803 	for (xcc = 0; xcc < num_xcc; xcc++)
1804 		amdgpu_mes_dbgext_setup_fw(adev, xcc, 0, 0);
1805 err_disable:
1806 	/* Undo the early arming done before setup_fw(). */
1807 	mes->dbgext_active = false;
1808 	if (use_irq)
1809 		mes->funcs->enable_dbgext_irq(mes, false);
1810 	mes->dbgext_use_irq = false;
1811 	/* Never free a kernel BO while suspended; keep it for the next start. */
1812 	if (!adev->in_suspend) {
1813 		amdgpu_bo_free_kernel(&mes->dbgext_log_gpu_obj,
1814 				      &mes->dbgext_log_gpu_addr,
1815 				      &mes->dbgext_log_cpu_addr);
1816 		mes->dbgext_log_size = 0;
1817 	}
1818 	return r;
1819 }
1820 
1821 int amdgpu_mes_dbgext_start(struct amdgpu_device *adev)
1822 {
1823 	int r;
1824 
1825 	mutex_lock(&adev->mes.dbgext_lock);
1826 	r = amdgpu_mes_dbgext_start_locked(adev);
1827 	mutex_unlock(&adev->mes.dbgext_lock);
1828 
1829 	return r;
1830 }
1831 
1832 static void amdgpu_mes_dbgext_stop_locked(struct amdgpu_device *adev)
1833 {
1834 	struct amdgpu_mes *mes = &adev->mes;
1835 
1836 	mes->dbgext_active = false;
1837 
1838 	/*
1839 	 * Tear down the reader kthread and the host interrupt first, and do so
1840 	 * independently of the buffer state.  The kthread runs code that lives
1841 	 * in this module, so it must never be left alive past module unload -
1842 	 * otherwise it faults on an instruction fetch once the module text is
1843 	 * freed.  A second stop() in a teardown/reset sequence, or one reached
1844 	 * after the buffer was already freed on an error path, must still be
1845 	 * able to reap a stale reader; hence this runs before the buffer guard.
1846 	 */
1847 	if (mes->dbgext_reader) {
1848 		kthread_stop(mes->dbgext_reader);
1849 		mes->dbgext_reader = NULL;
1850 	}
1851 
1852 	if (mes->dbgext_use_irq) {
1853 		mes->funcs->enable_dbgext_irq(mes, false);
1854 		mes->dbgext_use_irq = false;
1855 	}
1856 
1857 	if (!mes->dbgext_log_gpu_obj)
1858 		return;
1859 
1860 	/*
1861 	 * Detach the firmware from the buffer before we free it, on every XCC we
1862 	 * armed.  Skip this across a suspend: the MES is being torn down anyway,
1863 	 * the buffer is kept for resume, and submitting a packet on the suspend
1864 	 * path is unnecessary.
1865 	 */
1866 	if (!adev->in_suspend) {
1867 		u32 num_xcc = mes->dbgext_num_xcc ? mes->dbgext_num_xcc : 1;
1868 		u32 xcc;
1869 
1870 		for (xcc = 0; xcc < num_xcc; xcc++)
1871 			amdgpu_mes_dbgext_setup_fw(adev, xcc, 0, 0);
1872 	}
1873 
1874 	/* Make sure no drain work is still touching the buffer. */
1875 	cancel_work_sync(&mes->dbgext_work);
1876 
1877 	/* Drain anything the firmware wrote before we stopped. */
1878 	mes_dbgext_process_all(adev);
1879 
1880 	/*
1881 	 * Keep the buffer allocated across a suspend/resume cycle (freeing a
1882 	 * kernel BO while suspended is not allowed - it trips a WARN in
1883 	 * amdgpu_bo_free_kernel()); only free it on real teardown.
1884 	 */
1885 	if (adev->in_suspend)
1886 		return;
1887 
1888 	amdgpu_bo_free_kernel(&mes->dbgext_log_gpu_obj,
1889 			      &mes->dbgext_log_gpu_addr,
1890 			      &mes->dbgext_log_cpu_addr);
1891 	mes->dbgext_log_size = 0;
1892 }
1893 
1894 void amdgpu_mes_dbgext_stop(struct amdgpu_device *adev)
1895 {
1896 	mutex_lock(&adev->mes.dbgext_lock);
1897 	amdgpu_mes_dbgext_stop_locked(adev);
1898 	mutex_unlock(&adev->mes.dbgext_lock);
1899 }
1900 
1901 #if defined(CONFIG_DEBUG_FS)
1902 
1903 static int amdgpu_debugfs_mes_event_log_show(struct seq_file *m, void *unused)
1904 {
1905 	struct amdgpu_device *adev = m->private;
1906 	uint32_t *mem = (uint32_t *)(adev->mes.event_log_cpu_addr);
1907 
1908 	seq_hex_dump(m, "", DUMP_PREFIX_OFFSET, 32, 4,
1909 		     mem, adev->mes.event_log_size, false);
1910 
1911 	return 0;
1912 }
1913 
1914 DEFINE_SHOW_ATTRIBUTE(amdgpu_debugfs_mes_event_log);
1915 
1916 /*
1917  * Runtime on/off switch for the MES firmware debug extension.
1918  *
1919  *   cat  <debugfs>/amdgpu_mes_dbgext   -> current state / size / mode
1920  *   echo 1 > <debugfs>/amdgpu_mes_dbgext   -> enable
1921  *   echo 0 > <debugfs>/amdgpu_mes_dbgext   -> disable
1922  *
1923  * When enabled with no boot-time size (mes_dbgext_buffer_size=0) a default
1924  * buffer size is used; the collection method still follows mes_dbgext_options.
1925  */
1926 static int amdgpu_debugfs_mes_dbgext_show(struct seq_file *m, void *unused)
1927 {
1928 	struct amdgpu_device *adev = m->private;
1929 	struct amdgpu_mes *mes = &adev->mes;
1930 
1931 	mutex_lock(&mes->dbgext_lock);
1932 	seq_printf(m, "state:   %s\n", mes->dbgext_active ? "on" : "off");
1933 	seq_printf(m, "size:    %u KB x %u xcc\n", mes->dbgext_log_size / SZ_1K,
1934 		   mes->dbgext_num_xcc ? mes->dbgext_num_xcc : 1);
1935 	seq_printf(m, "mode:    %s\n",
1936 		   mes->dbgext_use_irq ? "interrupt" : "polling");
1937 	seq_printf(m, "options: 0x%llx\n", mes->dbgext_log_options);
1938 	mutex_unlock(&mes->dbgext_lock);
1939 
1940 	return 0;
1941 }
1942 
1943 static int amdgpu_debugfs_mes_dbgext_open(struct inode *inode, struct file *file)
1944 {
1945 	return single_open(file, amdgpu_debugfs_mes_dbgext_show,
1946 			   inode->i_private);
1947 }
1948 
1949 static ssize_t amdgpu_debugfs_mes_dbgext_write(struct file *file,
1950 					       const char __user *buf,
1951 					       size_t count, loff_t *ppos)
1952 {
1953 	struct amdgpu_device *adev =
1954 		((struct seq_file *)file->private_data)->private;
1955 	struct amdgpu_mes *mes = &adev->mes;
1956 	bool enable;
1957 	int r;
1958 
1959 	r = kstrtobool_from_user(buf, count, &enable);
1960 	if (r)
1961 		return r;
1962 
1963 	if (!mes->funcs || !mes->funcs->misc_op)
1964 		return -EOPNOTSUPP;
1965 
1966 	mutex_lock(&mes->dbgext_lock);
1967 	if (enable) {
1968 		mes->dbgext_runtime_kb = amdgpu_mes_dbgext_buffer_size ?
1969 			amdgpu_mes_dbgext_buffer_size : MES_DBGEXT_DEFAULT_KB;
1970 		r = amdgpu_mes_dbgext_start_locked(adev);
1971 	} else {
1972 		amdgpu_mes_dbgext_stop_locked(adev);
1973 		mes->dbgext_runtime_kb = 0;
1974 		r = 0;
1975 	}
1976 	mutex_unlock(&mes->dbgext_lock);
1977 
1978 	return r ? r : count;
1979 }
1980 
1981 static const struct file_operations amdgpu_debugfs_mes_dbgext_fops = {
1982 	.owner = THIS_MODULE,
1983 	.open = amdgpu_debugfs_mes_dbgext_open,
1984 	.read = seq_read,
1985 	.write = amdgpu_debugfs_mes_dbgext_write,
1986 	.llseek = seq_lseek,
1987 	.release = single_release,
1988 };
1989 
1990 #endif
1991 
1992 void amdgpu_debugfs_mes_init(struct amdgpu_device *adev)
1993 {
1994 #if defined(CONFIG_DEBUG_FS)
1995 	struct drm_minor *minor = adev_to_drm(adev)->primary;
1996 	struct dentry *root = minor->debugfs_root;
1997 
1998 	if (!adev->enable_mes)
1999 		return;
2000 
2001 	if (amdgpu_mes_log_enable)
2002 		debugfs_create_file("amdgpu_mes_event_log", 0444, root,
2003 				    adev, &amdgpu_debugfs_mes_event_log_fops);
2004 
2005 	debugfs_create_file("amdgpu_mes_dbgext", 0644, root,
2006 			    adev, &amdgpu_debugfs_mes_dbgext_fops);
2007 #endif
2008 }
2009