xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gfx.c (revision b6f466c509ad2f390b3fc91cd0de4783554f5f98)
1 /*
2  * Copyright 2014 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */
25 
26 #include <linux/firmware.h>
27 #include <linux/pm_runtime.h>
28 
29 #include "amdgpu.h"
30 #include "amdgpu_gfx.h"
31 #include "amdgpu_rlc.h"
32 #include "amdgpu_ras.h"
33 #include "amdgpu_reset.h"
34 #include "amdgpu_xcp.h"
35 #include "amdgpu_xgmi.h"
36 #include "amdgpu_mes.h"
37 #include "mes_userqueue.h"
38 #include "nvd.h"
39 
40 /* delay 0.1 second to enable gfx off feature */
41 #define GFX_OFF_DELAY_ENABLE         msecs_to_jiffies(100)
42 
43 #define GFX_OFF_NO_DELAY 0
44 
45 /*
46  * GPU GFX IP block helpers function.
47  */
48 
49 int amdgpu_gfx_mec_queue_to_bit(struct amdgpu_device *adev, int mec,
50 				int pipe, int queue)
51 {
52 	int bit = 0;
53 
54 	bit += mec * adev->gfx.mec.num_pipe_per_mec
55 		* adev->gfx.mec.num_queue_per_pipe;
56 	bit += pipe * adev->gfx.mec.num_queue_per_pipe;
57 	bit += queue;
58 
59 	return bit;
60 }
61 
62 void amdgpu_queue_mask_bit_to_mec_queue(struct amdgpu_device *adev, int bit,
63 				 int *mec, int *pipe, int *queue)
64 {
65 	*queue = bit % adev->gfx.mec.num_queue_per_pipe;
66 	*pipe = (bit / adev->gfx.mec.num_queue_per_pipe)
67 		% adev->gfx.mec.num_pipe_per_mec;
68 	*mec = (bit / adev->gfx.mec.num_queue_per_pipe)
69 	       / adev->gfx.mec.num_pipe_per_mec;
70 
71 }
72 
73 bool amdgpu_gfx_is_mec_queue_enabled(struct amdgpu_device *adev,
74 				     int xcc_id, int mec, int pipe, int queue)
75 {
76 	return test_bit(amdgpu_gfx_mec_queue_to_bit(adev, mec, pipe, queue),
77 			adev->gfx.mec_bitmap[xcc_id].queue_bitmap);
78 }
79 
80 static int amdgpu_gfx_me_queue_to_bit(struct amdgpu_device *adev,
81 				      int me, int pipe, int queue)
82 {
83 	int num_queue_per_pipe = 1; /* we only enable 1 KGQ per pipe */
84 	int bit = 0;
85 
86 	bit += me * adev->gfx.me.num_pipe_per_me
87 		* num_queue_per_pipe;
88 	bit += pipe * num_queue_per_pipe;
89 	bit += queue;
90 
91 	return bit;
92 }
93 
94 bool amdgpu_gfx_is_me_queue_enabled(struct amdgpu_device *adev,
95 				    int me, int pipe, int queue)
96 {
97 	return test_bit(amdgpu_gfx_me_queue_to_bit(adev, me, pipe, queue),
98 			adev->gfx.me.queue_bitmap);
99 }
100 
101 /**
102  * amdgpu_gfx_parse_disable_cu - Parse the disable_cu module parameter
103  *
104  * @adev: amdgpu device pointer
105  * @mask: array in which the per-shader array disable masks will be stored
106  * @max_se: number of SEs
107  * @max_sh: number of SHs
108  *
109  * The bitmask of CUs to be disabled in the shader array determined by se and
110  * sh is stored in mask[se * max_sh + sh].
111  */
112 void amdgpu_gfx_parse_disable_cu(struct amdgpu_device *adev, unsigned int *mask,
113 				 unsigned int max_se, unsigned int max_sh)
114 {
115 	unsigned int se, sh, cu;
116 	const char *p;
117 
118 	memset(mask, 0, sizeof(*mask) * max_se * max_sh);
119 
120 	if (!amdgpu_disable_cu || !*amdgpu_disable_cu)
121 		return;
122 
123 	p = amdgpu_disable_cu;
124 	for (;;) {
125 		char *next;
126 		int ret = sscanf(p, "%u.%u.%u", &se, &sh, &cu);
127 
128 		if (ret < 3) {
129 			drm_err(adev_to_drm(adev), "could not parse disable_cu\n");
130 			return;
131 		}
132 
133 		if (se < max_se && sh < max_sh && cu < 16) {
134 			drm_info(adev_to_drm(adev), "Disabling CU %u.%u.%u\n", se, sh, cu);
135 			mask[se * max_sh + sh] |= 1u << cu;
136 		} else {
137 			drm_err(adev_to_drm(adev), "disable_cu %u.%u.%u is out of range\n",
138 				se, sh, cu);
139 		}
140 
141 		next = strchr(p, ',');
142 		if (!next)
143 			break;
144 		p = next + 1;
145 	}
146 }
147 
148 static bool amdgpu_gfx_is_graphics_multipipe_capable(struct amdgpu_device *adev)
149 {
150 	return amdgpu_async_gfx_ring && adev->gfx.me.num_pipe_per_me > 1;
151 }
152 
153 static bool amdgpu_gfx_is_compute_multipipe_capable(struct amdgpu_device *adev)
154 {
155 	if (amdgpu_compute_multipipe != -1) {
156 		dev_info(adev->dev, " forcing compute pipe policy %d\n",
157 			 amdgpu_compute_multipipe);
158 		return amdgpu_compute_multipipe == 1;
159 	}
160 
161 	if (amdgpu_ip_version(adev, GC_HWIP, 0) > IP_VERSION(9, 0, 0))
162 		return true;
163 
164 	/* FIXME: spreading the queues across pipes causes perf regressions
165 	 * on POLARIS11 compute workloads */
166 	if (adev->asic_type == CHIP_POLARIS11)
167 		return false;
168 
169 	return adev->gfx.mec.num_mec > 1;
170 }
171 
172 bool amdgpu_gfx_is_high_priority_graphics_queue(struct amdgpu_device *adev,
173 						struct amdgpu_ring *ring)
174 {
175 	int queue = ring->queue;
176 	int pipe = ring->pipe;
177 
178 	/* Policy: use pipe1 queue0 as high priority graphics queue if we
179 	 * have more than one gfx pipe.
180 	 */
181 	if (amdgpu_gfx_is_graphics_multipipe_capable(adev) &&
182 	    adev->gfx.num_gfx_rings > 1 && pipe == 1 && queue == 0) {
183 		int me = ring->me;
184 		int bit;
185 
186 		bit = amdgpu_gfx_me_queue_to_bit(adev, me, pipe, queue);
187 		if (ring == &adev->gfx.gfx_ring[bit])
188 			return true;
189 	}
190 
191 	return false;
192 }
193 
194 bool amdgpu_gfx_is_high_priority_compute_queue(struct amdgpu_device *adev,
195 					       struct amdgpu_ring *ring)
196 {
197 	/* Policy: use 1st queue as high priority compute queue if we
198 	 * have more than one compute queue.
199 	 */
200 	if (adev->gfx.num_compute_rings > 1 &&
201 	    ring == &adev->gfx.compute_ring[0])
202 		return true;
203 
204 	return false;
205 }
206 
207 void amdgpu_gfx_compute_queue_acquire(struct amdgpu_device *adev)
208 {
209 	int i, j, queue, pipe;
210 	bool multipipe_policy = amdgpu_gfx_is_compute_multipipe_capable(adev);
211 	int max_queues_per_mec = min(adev->gfx.mec.num_pipe_per_mec *
212 				     adev->gfx.mec.num_queue_per_pipe,
213 				     adev->gfx.num_compute_rings);
214 	int num_xcc = adev->gfx.xcc_mask ? NUM_XCC(adev->gfx.xcc_mask) : 1;
215 
216 	if (multipipe_policy) {
217 		/* policy: make queues evenly cross all pipes on MEC1 only
218 		 * for multiple xcc, just use the original policy for simplicity */
219 		for (j = 0; j < num_xcc; j++) {
220 			for (i = 0; i < max_queues_per_mec; i++) {
221 				pipe = i % adev->gfx.mec.num_pipe_per_mec;
222 				queue = (i / adev->gfx.mec.num_pipe_per_mec) %
223 					 adev->gfx.mec.num_queue_per_pipe;
224 
225 				set_bit(pipe * adev->gfx.mec.num_queue_per_pipe + queue,
226 					adev->gfx.mec_bitmap[j].queue_bitmap);
227 			}
228 		}
229 	} else {
230 		/* policy: amdgpu owns all queues in the given pipe */
231 		for (j = 0; j < num_xcc; j++) {
232 			for (i = 0; i < max_queues_per_mec; ++i)
233 				set_bit(i, adev->gfx.mec_bitmap[j].queue_bitmap);
234 		}
235 	}
236 
237 	for (j = 0; j < num_xcc; j++) {
238 		dev_dbg(adev->dev, "mec queue bitmap weight=%d\n",
239 			bitmap_weight(adev->gfx.mec_bitmap[j].queue_bitmap, AMDGPU_MAX_COMPUTE_QUEUES));
240 	}
241 }
242 
243 void amdgpu_gfx_graphics_queue_acquire(struct amdgpu_device *adev)
244 {
245 	int i, queue, pipe;
246 	bool multipipe_policy = amdgpu_gfx_is_graphics_multipipe_capable(adev);
247 	int num_queue_per_pipe = 1; /* we only enable 1 KGQ per pipe */
248 	int max_queues_per_me = adev->gfx.me.num_pipe_per_me * num_queue_per_pipe;
249 
250 	if (multipipe_policy) {
251 		/* policy: amdgpu owns the first queue per pipe at this stage
252 		 * will extend to mulitple queues per pipe later */
253 		for (i = 0; i < max_queues_per_me; i++) {
254 			pipe = i % adev->gfx.me.num_pipe_per_me;
255 			queue = (i / adev->gfx.me.num_pipe_per_me) %
256 				num_queue_per_pipe;
257 
258 			set_bit(pipe * num_queue_per_pipe + queue,
259 				adev->gfx.me.queue_bitmap);
260 		}
261 	} else {
262 		for (i = 0; i < max_queues_per_me; ++i)
263 			set_bit(i, adev->gfx.me.queue_bitmap);
264 	}
265 
266 	/* update the number of active graphics rings */
267 	if (adev->gfx.num_gfx_rings)
268 		adev->gfx.num_gfx_rings =
269 			bitmap_weight(adev->gfx.me.queue_bitmap, AMDGPU_MAX_GFX_QUEUES);
270 }
271 
272 static int amdgpu_gfx_kiq_acquire(struct amdgpu_device *adev,
273 				  struct amdgpu_ring *ring, int xcc_id)
274 {
275 	int queue_bit;
276 	int mec, pipe, queue;
277 
278 	queue_bit = adev->gfx.mec.num_mec
279 		    * adev->gfx.mec.num_pipe_per_mec
280 		    * adev->gfx.mec.num_queue_per_pipe;
281 
282 	while (--queue_bit >= 0) {
283 		if (test_bit(queue_bit, adev->gfx.mec_bitmap[xcc_id].queue_bitmap))
284 			continue;
285 
286 		amdgpu_queue_mask_bit_to_mec_queue(adev, queue_bit, &mec, &pipe, &queue);
287 
288 		/*
289 		 * 1. Using pipes 2/3 from MEC 2 seems cause problems.
290 		 * 2. It must use queue id 0, because CGPG_IDLE/SAVE/LOAD/RUN
291 		 * only can be issued on queue 0.
292 		 */
293 		if ((mec == 1 && pipe > 1) || queue != 0)
294 			continue;
295 
296 		ring->me = mec + 1;
297 		ring->pipe = pipe;
298 		ring->queue = queue;
299 
300 		return 0;
301 	}
302 
303 	dev_err(adev->dev, "Failed to find a queue for KIQ\n");
304 	return -EINVAL;
305 }
306 
307 int amdgpu_gfx_kiq_init_ring(struct amdgpu_device *adev, int xcc_id)
308 {
309 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
310 	struct amdgpu_irq_src *irq = &kiq->irq;
311 	struct amdgpu_ring *ring = &kiq->ring;
312 	int r = 0;
313 
314 	spin_lock_init(&kiq->ring_lock);
315 
316 	ring->adev = NULL;
317 	ring->ring_obj = NULL;
318 	ring->use_doorbell = true;
319 	ring->xcc_id = xcc_id;
320 	ring->vm_hub = AMDGPU_GFXHUB(xcc_id);
321 	ring->doorbell_index =
322 		(adev->doorbell_index.kiq +
323 		 xcc_id * adev->doorbell_index.xcc_doorbell_range)
324 		<< 1;
325 
326 	r = amdgpu_gfx_kiq_acquire(adev, ring, xcc_id);
327 	if (r)
328 		return r;
329 
330 	ring->eop_gpu_addr = kiq->eop_gpu_addr;
331 	ring->no_scheduler = true;
332 	snprintf(ring->name, sizeof(ring->name), "kiq_%hhu.%hhu.%hhu.%hhu",
333 		 (unsigned char)xcc_id, (unsigned char)ring->me,
334 		 (unsigned char)ring->pipe, (unsigned char)ring->queue);
335 	r = amdgpu_ring_init(adev, ring, 1024, irq, AMDGPU_CP_KIQ_IRQ_DRIVER0,
336 			     AMDGPU_RING_PRIO_DEFAULT, NULL);
337 	if (r)
338 		dev_warn(adev->dev, "(%d) failed to init kiq ring\n", r);
339 
340 	return r;
341 }
342 
343 void amdgpu_gfx_kiq_free_ring(struct amdgpu_ring *ring)
344 {
345 	amdgpu_ring_fini(ring);
346 }
347 
348 void amdgpu_gfx_kiq_fini(struct amdgpu_device *adev, int xcc_id)
349 {
350 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
351 
352 	amdgpu_bo_free_kernel(&kiq->eop_obj, &kiq->eop_gpu_addr, NULL);
353 }
354 
355 int amdgpu_gfx_kiq_init(struct amdgpu_device *adev,
356 			unsigned int hpd_size, int xcc_id)
357 {
358 	int r;
359 	u32 *hpd;
360 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
361 
362 	r = amdgpu_bo_create_kernel(adev, hpd_size, PAGE_SIZE,
363 				    AMDGPU_GEM_DOMAIN_GTT, &kiq->eop_obj,
364 				    &kiq->eop_gpu_addr, (void **)&hpd);
365 	if (r) {
366 		dev_warn(adev->dev, "failed to create KIQ bo (%d).\n", r);
367 		return r;
368 	}
369 
370 	memset(hpd, 0, hpd_size);
371 
372 	r = amdgpu_bo_reserve(kiq->eop_obj, true);
373 	if (unlikely(r != 0))
374 		dev_warn(adev->dev, "(%d) reserve kiq eop bo failed\n", r);
375 	amdgpu_bo_kunmap(kiq->eop_obj);
376 	amdgpu_bo_unreserve(kiq->eop_obj);
377 
378 	return 0;
379 }
380 
381 static void amdgpu_gfx_mqd_reset_restore(struct amdgpu_ring *ring)
382 {
383 	struct amdgpu_device *adev = ring->adev;
384 	int mqd_idx, mqd_size;
385 
386 	/* restore mqd with the backup copy */
387 	if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE) {
388 		mqd_idx = ring - &adev->gfx.compute_ring[0];
389 		mqd_size = adev->mqds[AMDGPU_HW_IP_COMPUTE].mqd_size;
390 		if (adev->gfx.mec.mqd_backup[mqd_idx])
391 			memcpy_toio(ring->mqd_ptr, adev->gfx.mec.mqd_backup[mqd_idx], mqd_size);
392 	} else if (ring->funcs->type == AMDGPU_RING_TYPE_GFX) {
393 		mqd_size = adev->mqds[AMDGPU_HW_IP_GFX].mqd_size;
394 		mqd_idx = ring - &adev->gfx.gfx_ring[0];
395 
396 		if (adev->gfx.me.mqd_backup[mqd_idx])
397 			memcpy_toio(ring->mqd_ptr, adev->gfx.me.mqd_backup[mqd_idx], mqd_size);
398 	}
399 	/* reset the ring */
400 	ring->wptr = 0;
401 	atomic64_set((atomic64_t *)ring->wptr_cpu_addr, 0);
402 	amdgpu_ring_clear_ring(ring);
403 }
404 
405 /* create MQD for each compute/gfx queue */
406 int amdgpu_gfx_mqd_sw_init(struct amdgpu_device *adev,
407 			   unsigned int mqd_size, int xcc_id)
408 {
409 	int r, i, j;
410 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
411 	struct amdgpu_ring *ring = &kiq->ring;
412 	u32 domain = AMDGPU_GEM_DOMAIN_GTT;
413 	u32 gfx_mqd_size = max(adev->mqds[AMDGPU_HW_IP_GFX].mqd_size, mqd_size);
414 	u32 compute_mqd_size = max(adev->mqds[AMDGPU_HW_IP_COMPUTE].mqd_size, mqd_size);
415 
416 #if !defined(CONFIG_ARM) && !defined(CONFIG_ARM64)
417 	/* Only enable on gfx10 and 11 for now to avoid changing behavior on older chips */
418 	if (amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(10, 0, 0))
419 		domain |= AMDGPU_GEM_DOMAIN_VRAM;
420 #endif
421 
422 	/* create MQD for KIQ */
423 	if (!adev->enable_mes_kiq && !ring->mqd_obj) {
424 		/* originaly the KIQ MQD is put in GTT domain, but for SRIOV VRAM domain is a must
425 		 * otherwise hypervisor trigger SAVE_VF fail after driver unloaded which mean MQD
426 		 * deallocated and gart_unbind, to strict diverage we decide to use VRAM domain for
427 		 * KIQ MQD no matter SRIOV or Bare-metal
428 		 */
429 		r = amdgpu_bo_create_kernel(adev, mqd_size, PAGE_SIZE,
430 					    AMDGPU_GEM_DOMAIN_VRAM |
431 					    AMDGPU_GEM_DOMAIN_GTT,
432 					    &ring->mqd_obj,
433 					    &ring->mqd_gpu_addr,
434 					    &ring->mqd_ptr);
435 		if (r) {
436 			dev_warn(adev->dev, "failed to create ring mqd ob (%d)", r);
437 			return r;
438 		}
439 
440 		/* prepare MQD backup */
441 		kiq->mqd_backup = kzalloc(mqd_size, GFP_KERNEL);
442 		if (!kiq->mqd_backup) {
443 			dev_warn(adev->dev,
444 				 "no memory to create MQD backup for ring %s\n", ring->name);
445 			return -ENOMEM;
446 		}
447 	}
448 
449 	if (adev->asic_type >= CHIP_NAVI10 && amdgpu_async_gfx_ring) {
450 		/* create MQD for each KGQ */
451 		for (i = 0; i < adev->gfx.num_gfx_rings; i++) {
452 			ring = &adev->gfx.gfx_ring[i];
453 			if (!ring->mqd_obj) {
454 				r = amdgpu_bo_create_kernel(adev, AMDGPU_MQD_SIZE_ALIGN(gfx_mqd_size),
455 								PAGE_SIZE, domain, &ring->mqd_obj,
456 							    &ring->mqd_gpu_addr, &ring->mqd_ptr);
457 				if (r) {
458 					dev_warn(adev->dev, "failed to create ring mqd bo (%d)", r);
459 					return r;
460 				}
461 
462 				ring->mqd_size = gfx_mqd_size;
463 				/* prepare MQD backup */
464 				adev->gfx.me.mqd_backup[i] = kzalloc(gfx_mqd_size, GFP_KERNEL);
465 				if (!adev->gfx.me.mqd_backup[i]) {
466 					dev_warn(adev->dev, "no memory to create MQD backup for ring %s\n", ring->name);
467 					return -ENOMEM;
468 				}
469 			}
470 		}
471 	}
472 
473 	/* create MQD for each KCQ */
474 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
475 		j = i + xcc_id * adev->gfx.num_compute_rings;
476 		ring = &adev->gfx.compute_ring[j];
477 		if (!ring->mqd_obj) {
478 			r = amdgpu_bo_create_kernel(adev, AMDGPU_MQD_SIZE_ALIGN(compute_mqd_size),
479 							PAGE_SIZE, domain, &ring->mqd_obj,
480 						    &ring->mqd_gpu_addr, &ring->mqd_ptr);
481 			if (r) {
482 				dev_warn(adev->dev, "failed to create ring mqd bo (%d)", r);
483 				return r;
484 			}
485 
486 			ring->mqd_size = compute_mqd_size;
487 			/* prepare MQD backup */
488 			adev->gfx.mec.mqd_backup[j] = kzalloc(compute_mqd_size, GFP_KERNEL);
489 			if (!adev->gfx.mec.mqd_backup[j]) {
490 				dev_warn(adev->dev, "no memory to create MQD backup for ring %s\n", ring->name);
491 				return -ENOMEM;
492 			}
493 		}
494 	}
495 
496 	return 0;
497 }
498 
499 void amdgpu_gfx_mqd_sw_fini(struct amdgpu_device *adev, int xcc_id)
500 {
501 	struct amdgpu_ring *ring = NULL;
502 	int i, j;
503 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
504 
505 	if (adev->asic_type >= CHIP_NAVI10 && amdgpu_async_gfx_ring) {
506 		for (i = 0; i < adev->gfx.num_gfx_rings; i++) {
507 			ring = &adev->gfx.gfx_ring[i];
508 			kfree(adev->gfx.me.mqd_backup[i]);
509 			amdgpu_bo_free_kernel(&ring->mqd_obj,
510 					      &ring->mqd_gpu_addr,
511 					      &ring->mqd_ptr);
512 		}
513 	}
514 
515 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
516 		j = i + xcc_id * adev->gfx.num_compute_rings;
517 		ring = &adev->gfx.compute_ring[j];
518 		kfree(adev->gfx.mec.mqd_backup[j]);
519 		amdgpu_bo_free_kernel(&ring->mqd_obj,
520 				      &ring->mqd_gpu_addr,
521 				      &ring->mqd_ptr);
522 	}
523 
524 	ring = &kiq->ring;
525 	kfree(kiq->mqd_backup);
526 	amdgpu_bo_free_kernel(&ring->mqd_obj,
527 			      &ring->mqd_gpu_addr,
528 			      &ring->mqd_ptr);
529 }
530 
531 void amdgpu_gfx_mqd_symmetrically_map_cu_mask(struct amdgpu_device *adev, const uint32_t *cu_mask,
532 					      uint32_t cu_mask_count, uint32_t *se_mask)
533 {
534 	struct amdgpu_cu_info *cu_info = &adev->gfx.cu_info;
535 	struct amdgpu_gfx_config *gfx_info = &adev->gfx.config;
536 	uint32_t cu_per_sh[8][4] = {0};
537 	int i, se, sh, cu, cu_bitmap_sh_mul;
538 	int xcc_inst = ffs(adev->gfx.xcc_mask) - 1;
539 	bool wgp_mode_req = amdgpu_ip_version(adev, GC_HWIP, 0) >= IP_VERSION(10, 0, 0);
540 	int cu_inc = wgp_mode_req ? 2 : 1;
541 	uint32_t en_mask = wgp_mode_req ? 0x3 : 0x1;
542 	int num_xcc, inc, inst = 0;
543 
544 	if (xcc_inst < 0)
545 		xcc_inst = 0;
546 
547 	num_xcc = hweight16(adev->gfx.xcc_mask);
548 	if (!num_xcc)
549 		num_xcc = 1;
550 
551 	inc = cu_inc * num_xcc;
552 
553 	cu_bitmap_sh_mul = 2;
554 
555 	for (se = 0; se < gfx_info->max_shader_engines; se++)
556 		for (sh = 0; sh < gfx_info->max_sh_per_se; sh++)
557 			cu_per_sh[se][sh] = hweight32(
558 				cu_info->bitmap[xcc_inst][se % 4][sh + (se / 4) *
559 				cu_bitmap_sh_mul]);
560 
561 	for (i = 0; i < gfx_info->max_shader_engines; i++)
562 		se_mask[i] = 0;
563 
564 	i = inst;
565 	for (cu = 0; cu < 16; cu += cu_inc) {
566 		for (sh = 0; sh < gfx_info->max_sh_per_se; sh++) {
567 			for (se = 0; se < gfx_info->max_shader_engines; se++) {
568 				if (cu_per_sh[se][sh] > cu) {
569 					if ((i / 32) < cu_mask_count && (cu_mask[i / 32] & (1 << (i % 32))))
570 						se_mask[se] |= en_mask << (cu + sh * 16);
571 					i += inc;
572 					if (i >= cu_mask_count * 32)
573 						return;
574 				}
575 			}
576 		}
577 	}
578 }
579 
580 int amdgpu_gfx_disable_kcq(struct amdgpu_device *adev, int xcc_id)
581 {
582 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
583 	struct amdgpu_ring *kiq_ring = &kiq->ring;
584 	int i, r = 0;
585 	int j;
586 
587 	if (adev->enable_mes) {
588 		for (i = 0; i < adev->gfx.num_compute_rings; i++) {
589 			j = i + xcc_id * adev->gfx.num_compute_rings;
590 			amdgpu_mes_unmap_legacy_queue(adev,
591 						   &adev->gfx.compute_ring[j],
592 						   RESET_QUEUES, 0, 0, xcc_id);
593 		}
594 		return 0;
595 	}
596 
597 	if (!kiq->pmf || !kiq->pmf->kiq_unmap_queues)
598 		return -EINVAL;
599 
600 	if (!kiq_ring->sched.ready || amdgpu_in_reset(adev))
601 		return 0;
602 
603 	spin_lock(&kiq->ring_lock);
604 	if (amdgpu_ring_alloc(kiq_ring, kiq->pmf->unmap_queues_size *
605 					adev->gfx.num_compute_rings)) {
606 		spin_unlock(&kiq->ring_lock);
607 		return -ENOMEM;
608 	}
609 
610 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
611 		j = i + xcc_id * adev->gfx.num_compute_rings;
612 		kiq->pmf->kiq_unmap_queues(kiq_ring,
613 					   &adev->gfx.compute_ring[j],
614 					   RESET_QUEUES, 0, 0);
615 	}
616 	/* Submit unmap queue packet */
617 	amdgpu_ring_commit(kiq_ring);
618 	/*
619 	 * Ring test will do a basic scratch register change check. Just run
620 	 * this to ensure that unmap queues that is submitted before got
621 	 * processed successfully before returning.
622 	 */
623 	r = amdgpu_ring_test_helper(kiq_ring);
624 
625 	spin_unlock(&kiq->ring_lock);
626 
627 	return r;
628 }
629 
630 int amdgpu_gfx_disable_kgq(struct amdgpu_device *adev, int xcc_id)
631 {
632 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
633 	struct amdgpu_ring *kiq_ring = &kiq->ring;
634 	int i, r = 0;
635 	int j;
636 
637 	if (adev->enable_mes) {
638 		if (amdgpu_gfx_is_master_xcc(adev, xcc_id)) {
639 			for (i = 0; i < adev->gfx.num_gfx_rings; i++) {
640 				j = i + xcc_id * adev->gfx.num_gfx_rings;
641 				amdgpu_mes_unmap_legacy_queue(adev,
642 						      &adev->gfx.gfx_ring[j],
643 						      PREEMPT_QUEUES, 0, 0, xcc_id);
644 			}
645 		}
646 		return 0;
647 	}
648 
649 	if (!kiq->pmf || !kiq->pmf->kiq_unmap_queues)
650 		return -EINVAL;
651 
652 	if (!adev->gfx.kiq[0].ring.sched.ready || amdgpu_in_reset(adev))
653 		return 0;
654 
655 	if (amdgpu_gfx_is_master_xcc(adev, xcc_id)) {
656 		spin_lock(&kiq->ring_lock);
657 		if (amdgpu_ring_alloc(kiq_ring, kiq->pmf->unmap_queues_size *
658 						adev->gfx.num_gfx_rings)) {
659 			spin_unlock(&kiq->ring_lock);
660 			return -ENOMEM;
661 		}
662 
663 		for (i = 0; i < adev->gfx.num_gfx_rings; i++) {
664 			j = i + xcc_id * adev->gfx.num_gfx_rings;
665 			kiq->pmf->kiq_unmap_queues(kiq_ring,
666 						   &adev->gfx.gfx_ring[j],
667 						   PREEMPT_QUEUES, 0, 0);
668 		}
669 		/* Submit unmap queue packet */
670 		amdgpu_ring_commit(kiq_ring);
671 
672 		/*
673 		 * Ring test will do a basic scratch register change check.
674 		 * Just run this to ensure that unmap queues that is submitted
675 		 * before got processed successfully before returning.
676 		 */
677 		r = amdgpu_ring_test_helper(kiq_ring);
678 		spin_unlock(&kiq->ring_lock);
679 	}
680 
681 	return r;
682 }
683 
684 int amdgpu_queue_mask_bit_to_set_resource_bit(struct amdgpu_device *adev,
685 					int queue_bit)
686 {
687 	int mec, pipe, queue;
688 	int set_resource_bit = 0;
689 
690 	amdgpu_queue_mask_bit_to_mec_queue(adev, queue_bit, &mec, &pipe, &queue);
691 
692 	set_resource_bit = mec * 4 * 8 + pipe * 8 + queue;
693 
694 	return set_resource_bit;
695 }
696 
697 static int amdgpu_gfx_mes_enable_kcq(struct amdgpu_device *adev, int xcc_id)
698 {
699 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
700 	struct amdgpu_ring *kiq_ring = &kiq->ring;
701 	uint64_t queue_mask = ~0ULL;
702 	int r, i, j;
703 
704 	amdgpu_device_flush_hdp(adev, NULL);
705 
706 	if (!adev->enable_uni_mes) {
707 		spin_lock(&kiq->ring_lock);
708 		r = amdgpu_ring_alloc(kiq_ring, kiq->pmf->set_resources_size);
709 		if (r) {
710 			dev_err(adev->dev, "Failed to lock KIQ (%d).\n", r);
711 			spin_unlock(&kiq->ring_lock);
712 			return r;
713 		}
714 
715 		kiq->pmf->kiq_set_resources(kiq_ring, queue_mask);
716 		r = amdgpu_ring_test_helper(kiq_ring);
717 		spin_unlock(&kiq->ring_lock);
718 		if (r)
719 			dev_err(adev->dev, "KIQ failed to set resources\n");
720 	}
721 
722 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
723 		j = i + xcc_id * adev->gfx.num_compute_rings;
724 		r = amdgpu_mes_map_legacy_queue(adev,
725 						&adev->gfx.compute_ring[j],
726 						xcc_id);
727 		if (r) {
728 			dev_err(adev->dev, "failed to map compute queue\n");
729 			return r;
730 		}
731 	}
732 
733 	return 0;
734 }
735 
736 int amdgpu_gfx_enable_kcq(struct amdgpu_device *adev, int xcc_id)
737 {
738 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
739 	struct amdgpu_ring *kiq_ring = &kiq->ring;
740 	uint64_t queue_mask = 0;
741 	int r, i, j;
742 
743 	if (adev->mes.enable_legacy_queue_map)
744 		return amdgpu_gfx_mes_enable_kcq(adev, xcc_id);
745 
746 	if (!kiq->pmf || !kiq->pmf->kiq_map_queues || !kiq->pmf->kiq_set_resources)
747 		return -EINVAL;
748 
749 	for (i = 0; i < AMDGPU_MAX_COMPUTE_QUEUES; ++i) {
750 		if (!test_bit(i, adev->gfx.mec_bitmap[xcc_id].queue_bitmap))
751 			continue;
752 
753 		/* This situation may be hit in the future if a new HW
754 		 * generation exposes more than 64 queues. If so, the
755 		 * definition of queue_mask needs updating */
756 		if (WARN_ON(i > (sizeof(queue_mask)*8))) {
757 			dev_err(adev->dev, "Invalid KCQ enabled: %d\n", i);
758 			break;
759 		}
760 
761 		queue_mask |= (1ull << amdgpu_queue_mask_bit_to_set_resource_bit(adev, i));
762 	}
763 
764 	amdgpu_device_flush_hdp(adev, NULL);
765 
766 	dev_info(adev->dev, "kiq ring mec %d pipe %d q %d\n", kiq_ring->me,
767 		 kiq_ring->pipe, kiq_ring->queue);
768 
769 	spin_lock(&kiq->ring_lock);
770 	r = amdgpu_ring_alloc(kiq_ring, kiq->pmf->map_queues_size *
771 					adev->gfx.num_compute_rings +
772 					kiq->pmf->set_resources_size);
773 	if (r) {
774 		dev_err(adev->dev, "Failed to lock KIQ (%d).\n", r);
775 		spin_unlock(&kiq->ring_lock);
776 		return r;
777 	}
778 
779 	kiq->pmf->kiq_set_resources(kiq_ring, queue_mask);
780 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
781 		j = i + xcc_id * adev->gfx.num_compute_rings;
782 		kiq->pmf->kiq_map_queues(kiq_ring,
783 					 &adev->gfx.compute_ring[j]);
784 	}
785 	/* Submit map queue packet */
786 	amdgpu_ring_commit(kiq_ring);
787 	/*
788 	 * Ring test will do a basic scratch register change check. Just run
789 	 * this to ensure that map queues that is submitted before got
790 	 * processed successfully before returning.
791 	 */
792 	r = amdgpu_ring_test_helper(kiq_ring);
793 	spin_unlock(&kiq->ring_lock);
794 	if (r)
795 		dev_err(adev->dev, "KCQ enable failed\n");
796 
797 	return r;
798 }
799 
800 int amdgpu_gfx_enable_kgq(struct amdgpu_device *adev, int xcc_id)
801 {
802 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
803 	struct amdgpu_ring *kiq_ring = &kiq->ring;
804 	int r, i, j;
805 
806 	if (!kiq->pmf || !kiq->pmf->kiq_map_queues)
807 		return -EINVAL;
808 
809 	amdgpu_device_flush_hdp(adev, NULL);
810 
811 	if (adev->mes.enable_legacy_queue_map) {
812 		for (i = 0; i < adev->gfx.num_gfx_rings; i++) {
813 			j = i + xcc_id * adev->gfx.num_gfx_rings;
814 			r = amdgpu_mes_map_legacy_queue(adev,
815 							&adev->gfx.gfx_ring[j],
816 							xcc_id);
817 			if (r) {
818 				dev_err(adev->dev, "failed to map gfx queue\n");
819 				return r;
820 			}
821 		}
822 
823 		return 0;
824 	}
825 
826 	spin_lock(&kiq->ring_lock);
827 	/* No need to map kcq on the slave */
828 	if (amdgpu_gfx_is_master_xcc(adev, xcc_id)) {
829 		r = amdgpu_ring_alloc(kiq_ring, kiq->pmf->map_queues_size *
830 						adev->gfx.num_gfx_rings);
831 		if (r) {
832 			dev_err(adev->dev, "Failed to lock KIQ (%d).\n", r);
833 			spin_unlock(&kiq->ring_lock);
834 			return r;
835 		}
836 
837 		for (i = 0; i < adev->gfx.num_gfx_rings; i++) {
838 			j = i + xcc_id * adev->gfx.num_gfx_rings;
839 			kiq->pmf->kiq_map_queues(kiq_ring,
840 						 &adev->gfx.gfx_ring[j]);
841 		}
842 	}
843 	/* Submit map queue packet */
844 	amdgpu_ring_commit(kiq_ring);
845 	/*
846 	 * Ring test will do a basic scratch register change check. Just run
847 	 * this to ensure that map queues that is submitted before got
848 	 * processed successfully before returning.
849 	 */
850 	r = amdgpu_ring_test_helper(kiq_ring);
851 	spin_unlock(&kiq->ring_lock);
852 	if (r)
853 		dev_err(adev->dev, "KGQ enable failed\n");
854 
855 	return r;
856 }
857 
858 static void amdgpu_gfx_do_off_ctrl(struct amdgpu_device *adev, bool enable,
859 				   bool no_delay)
860 {
861 	unsigned long delay = GFX_OFF_DELAY_ENABLE;
862 
863 	if (!(adev->pm.pp_feature & PP_GFXOFF_MASK))
864 		return;
865 
866 	mutex_lock(&adev->gfx.gfx_off_mutex);
867 
868 	if (enable) {
869 		/* If the count is already 0, it means there's an imbalance bug somewhere.
870 		 * Note that the bug may be in a different caller than the one which triggers the
871 		 * WARN_ON_ONCE.
872 		 */
873 		if (WARN_ON_ONCE(adev->gfx.gfx_off_req_count == 0))
874 			goto unlock;
875 
876 		adev->gfx.gfx_off_req_count--;
877 
878 		if (adev->gfx.gfx_off_req_count == 0 &&
879 		    !adev->gfx.gfx_off_state) {
880 			/* If going to s2idle, no need to wait */
881 			if (no_delay) {
882 				if (!amdgpu_dpm_set_powergating_by_smu(adev,
883 						AMD_IP_BLOCK_TYPE_GFX, true, 0))
884 					adev->gfx.gfx_off_state = true;
885 			} else {
886 				schedule_delayed_work(&adev->gfx.gfx_off_delay_work,
887 					      delay);
888 			}
889 		}
890 	} else {
891 		if (adev->gfx.gfx_off_req_count == 0) {
892 			cancel_delayed_work_sync(&adev->gfx.gfx_off_delay_work);
893 
894 			if (adev->gfx.gfx_off_state &&
895 			    !amdgpu_dpm_set_powergating_by_smu(adev, AMD_IP_BLOCK_TYPE_GFX, false, 0)) {
896 				adev->gfx.gfx_off_state = false;
897 
898 				if (adev->gfx.funcs->init_spm_golden) {
899 					dev_dbg(adev->dev,
900 						"GFXOFF is disabled, re-init SPM golden settings\n");
901 					amdgpu_gfx_init_spm_golden(adev);
902 				}
903 			}
904 		}
905 
906 		adev->gfx.gfx_off_req_count++;
907 	}
908 
909 unlock:
910 	mutex_unlock(&adev->gfx.gfx_off_mutex);
911 }
912 
913 /* amdgpu_gfx_off_ctrl - Handle gfx off feature enable/disable
914  *
915  * @adev: amdgpu_device pointer
916  * @bool enable true: enable gfx off feature, false: disable gfx off feature
917  *
918  * 1. gfx off feature will be enabled by gfx ip after gfx cg pg enabled.
919  * 2. other client can send request to disable gfx off feature, the request should be honored.
920  * 3. other client can cancel their request of disable gfx off feature
921  * 4. other client should not send request to enable gfx off feature before disable gfx off feature.
922  *
923  * gfx off allow will be delayed by GFX_OFF_DELAY_ENABLE ms.
924  */
925 void amdgpu_gfx_off_ctrl(struct amdgpu_device *adev, bool enable)
926 {
927 	/* If going to s2idle, no need to wait */
928 	bool no_delay = adev->in_s0ix ? true : false;
929 
930 	amdgpu_gfx_do_off_ctrl(adev, enable, no_delay);
931 }
932 
933 /* amdgpu_gfx_off_ctrl_immediate - Handle gfx off feature enable/disable
934  *
935  * @adev: amdgpu_device pointer
936  * @bool enable true: enable gfx off feature, false: disable gfx off feature
937  *
938  * 1. gfx off feature will be enabled by gfx ip after gfx cg pg enabled.
939  * 2. other client can send request to disable gfx off feature, the request should be honored.
940  * 3. other client can cancel their request of disable gfx off feature
941  * 4. other client should not send request to enable gfx off feature before disable gfx off feature.
942  *
943  * gfx off allow will be issued immediately.
944  */
945 void amdgpu_gfx_off_ctrl_immediate(struct amdgpu_device *adev, bool enable)
946 {
947 	amdgpu_gfx_do_off_ctrl(adev, enable, true);
948 }
949 
950 int amdgpu_set_gfx_off_residency(struct amdgpu_device *adev, bool value)
951 {
952 	int r = 0;
953 
954 	mutex_lock(&adev->gfx.gfx_off_mutex);
955 
956 	r = amdgpu_dpm_set_residency_gfxoff(adev, value);
957 
958 	mutex_unlock(&adev->gfx.gfx_off_mutex);
959 
960 	return r;
961 }
962 
963 int amdgpu_get_gfx_off_residency(struct amdgpu_device *adev, u32 *value)
964 {
965 	int r = 0;
966 
967 	mutex_lock(&adev->gfx.gfx_off_mutex);
968 
969 	r = amdgpu_dpm_get_residency_gfxoff(adev, value);
970 
971 	mutex_unlock(&adev->gfx.gfx_off_mutex);
972 
973 	return r;
974 }
975 
976 int amdgpu_get_gfx_off_entrycount(struct amdgpu_device *adev, u64 *value)
977 {
978 	int r = 0;
979 
980 	mutex_lock(&adev->gfx.gfx_off_mutex);
981 
982 	r = amdgpu_dpm_get_entrycount_gfxoff(adev, value);
983 
984 	mutex_unlock(&adev->gfx.gfx_off_mutex);
985 
986 	return r;
987 }
988 
989 int amdgpu_get_gfx_off_status(struct amdgpu_device *adev, uint32_t *value)
990 {
991 
992 	int r = 0;
993 
994 	mutex_lock(&adev->gfx.gfx_off_mutex);
995 
996 	r = amdgpu_dpm_get_status_gfxoff(adev, value);
997 
998 	mutex_unlock(&adev->gfx.gfx_off_mutex);
999 
1000 	return r;
1001 }
1002 
1003 int amdgpu_gfx_ras_late_init(struct amdgpu_device *adev, struct ras_common_if *ras_block)
1004 {
1005 	int r;
1006 
1007 	if (amdgpu_ras_is_supported(adev, ras_block->block)) {
1008 		if (!amdgpu_persistent_edc_harvesting_supported(adev)) {
1009 			r = amdgpu_ras_reset_error_status(adev, AMDGPU_RAS_BLOCK__GFX);
1010 			if (r)
1011 				return r;
1012 		}
1013 
1014 		r = amdgpu_ras_block_late_init(adev, ras_block);
1015 		if (r)
1016 			return r;
1017 
1018 		if (!amdgpu_sriov_vf(adev) && adev->gfx.cp_ecc_error_irq.funcs) {
1019 			r = amdgpu_irq_get(adev, &adev->gfx.cp_ecc_error_irq, 0);
1020 			if (r)
1021 				goto late_fini;
1022 		}
1023 	} else {
1024 		amdgpu_ras_feature_enable_on_boot(adev, ras_block, 0);
1025 	}
1026 
1027 	return 0;
1028 late_fini:
1029 	amdgpu_ras_block_late_fini(adev, ras_block);
1030 	return r;
1031 }
1032 
1033 void amdgpu_gfx_ras_suspend(struct amdgpu_device *adev,
1034 			    struct ras_common_if *ras_block)
1035 {
1036 	if (!amdgpu_sriov_vf(adev) && adev->gfx.cp_ecc_error_irq.funcs)
1037 		amdgpu_irq_put(adev, &adev->gfx.cp_ecc_error_irq, 0);
1038 }
1039 
1040 void amdgpu_gfx_ras_fini(struct amdgpu_device *adev,
1041 			 struct ras_common_if *ras_block)
1042 {
1043 	if (!amdgpu_sriov_vf(adev) && adev->gfx.cp_ecc_error_irq.funcs)
1044 		amdgpu_irq_put(adev, &adev->gfx.cp_ecc_error_irq, 0);
1045 	amdgpu_ras_block_late_fini(adev, ras_block);
1046 }
1047 
1048 int amdgpu_gfx_ras_sw_init(struct amdgpu_device *adev)
1049 {
1050 	int err = 0;
1051 	struct amdgpu_gfx_ras *ras = NULL;
1052 
1053 	/* adev->gfx.ras is NULL, which means gfx does not
1054 	 * support ras function, then do nothing here.
1055 	 */
1056 	if (!adev->gfx.ras)
1057 		return 0;
1058 
1059 	ras = adev->gfx.ras;
1060 
1061 	err = amdgpu_ras_register_ras_block(adev, &ras->ras_block);
1062 	if (err) {
1063 		dev_err(adev->dev, "Failed to register gfx ras block!\n");
1064 		return err;
1065 	}
1066 
1067 	strcpy(ras->ras_block.ras_comm.name, "gfx");
1068 	ras->ras_block.ras_comm.block = AMDGPU_RAS_BLOCK__GFX;
1069 	ras->ras_block.ras_comm.type = AMDGPU_RAS_ERROR__MULTI_UNCORRECTABLE;
1070 	adev->gfx.ras_if = &ras->ras_block.ras_comm;
1071 
1072 	/* If not define special ras_late_init function, use gfx default ras_late_init */
1073 	if (!ras->ras_block.ras_late_init)
1074 		ras->ras_block.ras_late_init = amdgpu_gfx_ras_late_init;
1075 
1076 	if (!ras->ras_block.ras_suspend)
1077 		ras->ras_block.ras_suspend = amdgpu_gfx_ras_suspend;
1078 
1079 	if (!ras->ras_block.ras_fini)
1080 		ras->ras_block.ras_fini = amdgpu_gfx_ras_fini;
1081 
1082 	/* If not defined special ras_cb function, use default ras_cb */
1083 	if (!ras->ras_block.ras_cb)
1084 		ras->ras_block.ras_cb = amdgpu_gfx_process_ras_data_cb;
1085 
1086 	return 0;
1087 }
1088 
1089 int amdgpu_gfx_poison_consumption_handler(struct amdgpu_device *adev,
1090 						struct amdgpu_iv_entry *entry)
1091 {
1092 	if (adev->gfx.ras && adev->gfx.ras->poison_consumption_handler)
1093 		return adev->gfx.ras->poison_consumption_handler(adev, entry);
1094 
1095 	return 0;
1096 }
1097 
1098 int amdgpu_gfx_process_ras_data_cb(struct amdgpu_device *adev,
1099 		void *err_data,
1100 		struct amdgpu_iv_entry *entry)
1101 {
1102 	/* TODO ue will trigger an interrupt.
1103 	 *
1104 	 * When “Full RAS” is enabled, the per-IP interrupt sources should
1105 	 * be disabled and the driver should only look for the aggregated
1106 	 * interrupt via sync flood
1107 	 */
1108 	if (!amdgpu_ras_is_supported(adev, AMDGPU_RAS_BLOCK__GFX)) {
1109 		kgd2kfd_set_sram_ecc_flag(adev->kfd.dev);
1110 		if (adev->gfx.ras && adev->gfx.ras->ras_block.hw_ops &&
1111 		    adev->gfx.ras->ras_block.hw_ops->query_ras_error_count)
1112 			adev->gfx.ras->ras_block.hw_ops->query_ras_error_count(adev, err_data);
1113 		amdgpu_ras_reset_gpu(adev);
1114 	}
1115 	return AMDGPU_RAS_SUCCESS;
1116 }
1117 
1118 int amdgpu_gfx_cp_ecc_error_irq(struct amdgpu_device *adev,
1119 				  struct amdgpu_irq_src *source,
1120 				  struct amdgpu_iv_entry *entry)
1121 {
1122 	struct ras_common_if *ras_if = adev->gfx.ras_if;
1123 	struct ras_dispatch_if ih_data = {
1124 		.entry = entry,
1125 	};
1126 
1127 	if (!ras_if)
1128 		return 0;
1129 
1130 	ih_data.head = *ras_if;
1131 
1132 	dev_err(adev->dev, "CP ECC ERROR IRQ\n");
1133 	amdgpu_ras_interrupt_dispatch(adev, &ih_data);
1134 	return 0;
1135 }
1136 
1137 void amdgpu_gfx_ras_error_func(struct amdgpu_device *adev,
1138 		void *ras_error_status,
1139 		void (*func)(struct amdgpu_device *adev, void *ras_error_status,
1140 				int xcc_id))
1141 {
1142 	int i;
1143 	int num_xcc = adev->gfx.xcc_mask ? NUM_XCC(adev->gfx.xcc_mask) : 1;
1144 	uint32_t xcc_mask = GENMASK(num_xcc - 1, 0);
1145 	struct ras_err_data *err_data = (struct ras_err_data *)ras_error_status;
1146 
1147 	if (err_data) {
1148 		err_data->ue_count = 0;
1149 		err_data->ce_count = 0;
1150 	}
1151 
1152 	for_each_inst(i, xcc_mask)
1153 		func(adev, ras_error_status, i);
1154 }
1155 
1156 uint32_t amdgpu_kiq_rreg(struct amdgpu_device *adev, uint32_t reg, uint32_t xcc_id)
1157 {
1158 	signed long r, cnt = 0;
1159 	unsigned long flags;
1160 	uint32_t seq, reg_val_offs = 0, value = 0;
1161 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
1162 	struct amdgpu_ring *ring = &kiq->ring;
1163 
1164 	if (amdgpu_device_skip_hw_access(adev))
1165 		return 0;
1166 
1167 	if (adev->mes.ring[0].sched.ready)
1168 		return amdgpu_mes_rreg(adev, reg, xcc_id);
1169 
1170 	BUG_ON(!ring->funcs->emit_rreg);
1171 
1172 	spin_lock_irqsave(&kiq->ring_lock, flags);
1173 	if (amdgpu_wb_get(adev, &reg_val_offs)) {
1174 		pr_err("critical bug! too many kiq readers\n");
1175 		goto failed_unlock;
1176 	}
1177 	r = amdgpu_ring_alloc(ring, 32);
1178 	if (r)
1179 		goto failed_unlock;
1180 
1181 	amdgpu_ring_emit_rreg(ring, reg, reg_val_offs);
1182 	r = amdgpu_fence_emit_polling(ring, &seq, MAX_KIQ_REG_WAIT);
1183 	if (r)
1184 		goto failed_undo;
1185 
1186 	amdgpu_ring_commit(ring);
1187 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
1188 
1189 	r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
1190 
1191 	/* don't wait anymore for gpu reset case because this way may
1192 	 * block gpu_recover() routine forever, e.g. this virt_kiq_rreg
1193 	 * is triggered in TTM and ttm_bo_lock_delayed_workqueue() will
1194 	 * never return if we keep waiting in virt_kiq_rreg, which cause
1195 	 * gpu_recover() hang there.
1196 	 *
1197 	 * also don't wait anymore for IRQ context
1198 	 * */
1199 	if (r < 1 && (amdgpu_in_reset(adev) || in_interrupt()))
1200 		goto failed_kiq_read;
1201 
1202 	might_sleep();
1203 	while (r < 1 && cnt++ < MAX_KIQ_REG_TRY) {
1204 		if (amdgpu_in_reset(adev))
1205 			goto failed_kiq_read;
1206 
1207 		msleep(MAX_KIQ_REG_BAILOUT_INTERVAL);
1208 		r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
1209 	}
1210 
1211 	if (cnt > MAX_KIQ_REG_TRY)
1212 		goto failed_kiq_read;
1213 
1214 	mb();
1215 	value = adev->wb.wb[reg_val_offs];
1216 	amdgpu_wb_free(adev, reg_val_offs);
1217 	return value;
1218 
1219 failed_undo:
1220 	amdgpu_ring_undo(ring);
1221 failed_unlock:
1222 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
1223 failed_kiq_read:
1224 	if (reg_val_offs)
1225 		amdgpu_wb_free(adev, reg_val_offs);
1226 	dev_err(adev->dev, "failed to read reg:%x\n", reg);
1227 	return ~0;
1228 }
1229 
1230 void amdgpu_kiq_wreg(struct amdgpu_device *adev, uint32_t reg, uint32_t v, uint32_t xcc_id)
1231 {
1232 	signed long r, cnt = 0;
1233 	unsigned long flags;
1234 	uint32_t seq;
1235 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[xcc_id];
1236 	struct amdgpu_ring *ring = &kiq->ring;
1237 
1238 	BUG_ON(!ring->funcs->emit_wreg);
1239 
1240 	if (amdgpu_device_skip_hw_access(adev))
1241 		return;
1242 
1243 	if (adev->mes.ring[0].sched.ready) {
1244 		amdgpu_mes_wreg(adev, reg, v, xcc_id);
1245 		return;
1246 	}
1247 
1248 	spin_lock_irqsave(&kiq->ring_lock, flags);
1249 	r = amdgpu_ring_alloc(ring, 32);
1250 	if (r)
1251 		goto failed_unlock;
1252 
1253 	amdgpu_ring_emit_wreg(ring, reg, v);
1254 	r = amdgpu_fence_emit_polling(ring, &seq, MAX_KIQ_REG_WAIT);
1255 	if (r)
1256 		goto failed_undo;
1257 
1258 	amdgpu_ring_commit(ring);
1259 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
1260 
1261 	r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
1262 
1263 	/* don't wait anymore for gpu reset case because this way may
1264 	 * block gpu_recover() routine forever, e.g. this virt_kiq_rreg
1265 	 * is triggered in TTM and ttm_bo_lock_delayed_workqueue() will
1266 	 * never return if we keep waiting in virt_kiq_rreg, which cause
1267 	 * gpu_recover() hang there.
1268 	 *
1269 	 * also don't wait anymore for IRQ context
1270 	 * */
1271 	if (r < 1 && (amdgpu_in_reset(adev) || in_interrupt()))
1272 		goto failed_kiq_write;
1273 
1274 	might_sleep();
1275 	while (r < 1 && cnt++ < MAX_KIQ_REG_TRY) {
1276 		if (amdgpu_in_reset(adev))
1277 			goto failed_kiq_write;
1278 
1279 		msleep(MAX_KIQ_REG_BAILOUT_INTERVAL);
1280 		r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
1281 	}
1282 
1283 	if (cnt > MAX_KIQ_REG_TRY)
1284 		goto failed_kiq_write;
1285 
1286 	return;
1287 
1288 failed_undo:
1289 	amdgpu_ring_undo(ring);
1290 failed_unlock:
1291 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
1292 failed_kiq_write:
1293 	dev_err(adev->dev, "failed to write reg:%x\n", reg);
1294 }
1295 
1296 void amdgpu_gfx_get_hdp_flush_mask(struct amdgpu_ring *ring,
1297 		uint32_t *hdp_flush_mask, uint32_t *reg_mem_engine)
1298 {
1299 
1300 	if (!ring || !hdp_flush_mask || !reg_mem_engine) {
1301 		DRM_INFO("%s:invalid params\n", __func__);
1302 		return;
1303 	}
1304 
1305 	const struct nbio_hdp_flush_reg *nbio_hf_reg = ring->adev->nbio.hdp_flush_reg;
1306 
1307 	switch (ring->funcs->type) {
1308 	case AMDGPU_RING_TYPE_GFX:
1309 		*hdp_flush_mask = nbio_hf_reg->ref_and_mask_cp0 << ring->pipe;
1310 		*reg_mem_engine = 1; /* pfp */
1311 		break;
1312 	case AMDGPU_RING_TYPE_COMPUTE:
1313 		*hdp_flush_mask = nbio_hf_reg->ref_and_mask_cp2 << ring->pipe;
1314 		*reg_mem_engine = 0;
1315 		break;
1316 	case AMDGPU_RING_TYPE_MES:
1317 		*hdp_flush_mask = nbio_hf_reg->ref_and_mask_cp8;
1318 		*reg_mem_engine = 0;
1319 		break;
1320 	case AMDGPU_RING_TYPE_KIQ:
1321 		*hdp_flush_mask = nbio_hf_reg->ref_and_mask_cp9;
1322 		*reg_mem_engine = 0;
1323 		break;
1324 	default:
1325 		DRM_ERROR("%s:unsupported ring type %d\n", __func__, ring->funcs->type);
1326 		return;
1327 	}
1328 }
1329 
1330 int amdgpu_kiq_hdp_flush(struct amdgpu_device *adev)
1331 {
1332 	signed long r, cnt = 0;
1333 	unsigned long flags;
1334 	uint32_t seq;
1335 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[0];
1336 	struct amdgpu_ring *ring = &kiq->ring;
1337 
1338 	if (amdgpu_device_skip_hw_access(adev))
1339 		return 0;
1340 
1341 	if (adev->enable_mes_kiq && adev->mes.ring[0].sched.ready)
1342 		return amdgpu_mes_hdp_flush(adev);
1343 
1344 	if (!ring->funcs->emit_hdp_flush) {
1345 		return -EOPNOTSUPP;
1346 	}
1347 
1348 	spin_lock_irqsave(&kiq->ring_lock, flags);
1349 	r = amdgpu_ring_alloc(ring, 32);
1350 	if (r)
1351 		goto failed_unlock;
1352 
1353 	amdgpu_ring_emit_hdp_flush(ring);
1354 	r = amdgpu_fence_emit_polling(ring, &seq, MAX_KIQ_REG_WAIT);
1355 	if (r)
1356 		goto failed_undo;
1357 
1358 	amdgpu_ring_commit(ring);
1359 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
1360 
1361 	r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
1362 
1363 	/* don't wait anymore for gpu reset case because this way may
1364 	 * block gpu_recover() routine forever, e.g. this virt_kiq_rreg
1365 	 * is triggered in TTM and ttm_bo_lock_delayed_workqueue() will
1366 	 * never return if we keep waiting in virt_kiq_rreg, which cause
1367 	 * gpu_recover() hang there.
1368 	 *
1369 	 * also don't wait anymore for IRQ context
1370 	 * */
1371 	if (r < 1 && (amdgpu_in_reset(adev) || in_interrupt()))
1372 		goto failed_kiq_hdp_flush;
1373 
1374 	might_sleep();
1375 	while (r < 1 && cnt++ < MAX_KIQ_REG_TRY) {
1376 		if (amdgpu_in_reset(adev))
1377 			goto failed_kiq_hdp_flush;
1378 
1379 		msleep(MAX_KIQ_REG_BAILOUT_INTERVAL);
1380 		r = amdgpu_fence_wait_polling(ring, seq, MAX_KIQ_REG_WAIT);
1381 	}
1382 
1383 	if (cnt > MAX_KIQ_REG_TRY) {
1384 		dev_err(adev->dev, "failed to flush HDP via KIQ timeout\n");
1385 		return -ETIMEDOUT;
1386 	}
1387 
1388 	return 0;
1389 
1390 failed_undo:
1391 	amdgpu_ring_undo(ring);
1392 failed_unlock:
1393 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
1394 failed_kiq_hdp_flush:
1395 	if (!amdgpu_in_reset(adev))
1396 		dev_err(adev->dev, "failed to flush HDP via KIQ\n");
1397 	return r < 0 ? r : -EIO;
1398 }
1399 
1400 int amdgpu_gfx_get_num_kcq(struct amdgpu_device *adev)
1401 {
1402 	if (amdgpu_num_kcq == -1) {
1403 		return 8;
1404 	} else if (amdgpu_num_kcq > 8 || amdgpu_num_kcq < 0) {
1405 		dev_warn(adev->dev, "set kernel compute queue number to 8 due to invalid parameter provided by user\n");
1406 		return 8;
1407 	}
1408 	return amdgpu_num_kcq;
1409 }
1410 
1411 void amdgpu_gfx_cp_init_microcode(struct amdgpu_device *adev,
1412 				  uint32_t ucode_id)
1413 {
1414 	const struct gfx_firmware_header_v1_0 *cp_hdr;
1415 	const struct gfx_firmware_header_v2_0 *cp_hdr_v2_0;
1416 	struct amdgpu_firmware_info *info = NULL;
1417 	const struct firmware *ucode_fw;
1418 	unsigned int fw_size;
1419 
1420 	switch (ucode_id) {
1421 	case AMDGPU_UCODE_ID_CP_PFP:
1422 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1423 			adev->gfx.pfp_fw->data;
1424 		adev->gfx.pfp_fw_version =
1425 			le32_to_cpu(cp_hdr->header.ucode_version);
1426 		adev->gfx.pfp_feature_version =
1427 			le32_to_cpu(cp_hdr->ucode_feature_version);
1428 		ucode_fw = adev->gfx.pfp_fw;
1429 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes);
1430 		break;
1431 	case AMDGPU_UCODE_ID_CP_RS64_PFP:
1432 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1433 			adev->gfx.pfp_fw->data;
1434 		adev->gfx.pfp_fw_version =
1435 			le32_to_cpu(cp_hdr_v2_0->header.ucode_version);
1436 		adev->gfx.pfp_feature_version =
1437 			le32_to_cpu(cp_hdr_v2_0->ucode_feature_version);
1438 		ucode_fw = adev->gfx.pfp_fw;
1439 		fw_size = le32_to_cpu(cp_hdr_v2_0->ucode_size_bytes);
1440 		break;
1441 	case AMDGPU_UCODE_ID_CP_RS64_PFP_P0_STACK:
1442 	case AMDGPU_UCODE_ID_CP_RS64_PFP_P1_STACK:
1443 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1444 			adev->gfx.pfp_fw->data;
1445 		ucode_fw = adev->gfx.pfp_fw;
1446 		fw_size = le32_to_cpu(cp_hdr_v2_0->data_size_bytes);
1447 		break;
1448 	case AMDGPU_UCODE_ID_CP_ME:
1449 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1450 			adev->gfx.me_fw->data;
1451 		adev->gfx.me_fw_version =
1452 			le32_to_cpu(cp_hdr->header.ucode_version);
1453 		adev->gfx.me_feature_version =
1454 			le32_to_cpu(cp_hdr->ucode_feature_version);
1455 		ucode_fw = adev->gfx.me_fw;
1456 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes);
1457 		break;
1458 	case AMDGPU_UCODE_ID_CP_RS64_ME:
1459 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1460 			adev->gfx.me_fw->data;
1461 		adev->gfx.me_fw_version =
1462 			le32_to_cpu(cp_hdr_v2_0->header.ucode_version);
1463 		adev->gfx.me_feature_version =
1464 			le32_to_cpu(cp_hdr_v2_0->ucode_feature_version);
1465 		ucode_fw = adev->gfx.me_fw;
1466 		fw_size = le32_to_cpu(cp_hdr_v2_0->ucode_size_bytes);
1467 		break;
1468 	case AMDGPU_UCODE_ID_CP_RS64_ME_P0_STACK:
1469 	case AMDGPU_UCODE_ID_CP_RS64_ME_P1_STACK:
1470 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1471 			adev->gfx.me_fw->data;
1472 		ucode_fw = adev->gfx.me_fw;
1473 		fw_size = le32_to_cpu(cp_hdr_v2_0->data_size_bytes);
1474 		break;
1475 	case AMDGPU_UCODE_ID_CP_CE:
1476 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1477 			adev->gfx.ce_fw->data;
1478 		adev->gfx.ce_fw_version =
1479 			le32_to_cpu(cp_hdr->header.ucode_version);
1480 		adev->gfx.ce_feature_version =
1481 			le32_to_cpu(cp_hdr->ucode_feature_version);
1482 		ucode_fw = adev->gfx.ce_fw;
1483 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes);
1484 		break;
1485 	case AMDGPU_UCODE_ID_CP_MEC1:
1486 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1487 			adev->gfx.mec_fw->data;
1488 		adev->gfx.mec_fw_version =
1489 			le32_to_cpu(cp_hdr->header.ucode_version);
1490 		adev->gfx.mec_feature_version =
1491 			le32_to_cpu(cp_hdr->ucode_feature_version);
1492 		ucode_fw = adev->gfx.mec_fw;
1493 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes) -
1494 			  le32_to_cpu(cp_hdr->jt_size) * 4;
1495 		break;
1496 	case AMDGPU_UCODE_ID_CP_MEC1_JT:
1497 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1498 			adev->gfx.mec_fw->data;
1499 		ucode_fw = adev->gfx.mec_fw;
1500 		fw_size = le32_to_cpu(cp_hdr->jt_size) * 4;
1501 		break;
1502 	case AMDGPU_UCODE_ID_CP_MEC2:
1503 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1504 			adev->gfx.mec2_fw->data;
1505 		adev->gfx.mec2_fw_version =
1506 			le32_to_cpu(cp_hdr->header.ucode_version);
1507 		adev->gfx.mec2_feature_version =
1508 			le32_to_cpu(cp_hdr->ucode_feature_version);
1509 		ucode_fw = adev->gfx.mec2_fw;
1510 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes) -
1511 			  le32_to_cpu(cp_hdr->jt_size) * 4;
1512 		break;
1513 	case AMDGPU_UCODE_ID_CP_MEC2_JT:
1514 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1515 			adev->gfx.mec2_fw->data;
1516 		ucode_fw = adev->gfx.mec2_fw;
1517 		fw_size = le32_to_cpu(cp_hdr->jt_size) * 4;
1518 		break;
1519 	case AMDGPU_UCODE_ID_CP_RS64_MEC:
1520 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1521 			adev->gfx.mec_fw->data;
1522 		adev->gfx.mec_fw_version =
1523 			le32_to_cpu(cp_hdr_v2_0->header.ucode_version);
1524 		adev->gfx.mec_feature_version =
1525 			le32_to_cpu(cp_hdr_v2_0->ucode_feature_version);
1526 		ucode_fw = adev->gfx.mec_fw;
1527 		fw_size = le32_to_cpu(cp_hdr_v2_0->ucode_size_bytes);
1528 		break;
1529 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P0_STACK:
1530 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P1_STACK:
1531 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P2_STACK:
1532 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P3_STACK:
1533 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1534 			adev->gfx.mec_fw->data;
1535 		ucode_fw = adev->gfx.mec_fw;
1536 		fw_size = le32_to_cpu(cp_hdr_v2_0->data_size_bytes);
1537 		break;
1538 	default:
1539 		dev_err(adev->dev, "Invalid ucode id %u\n", ucode_id);
1540 		return;
1541 	}
1542 
1543 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
1544 		info = &adev->firmware.ucode[ucode_id];
1545 		info->ucode_id = ucode_id;
1546 		info->fw = ucode_fw;
1547 		adev->firmware.fw_size += ALIGN(fw_size, PAGE_SIZE);
1548 	}
1549 }
1550 
1551 bool amdgpu_gfx_is_master_xcc(struct amdgpu_device *adev, int xcc_id)
1552 {
1553 	return !(xcc_id % (adev->gfx.num_xcc_per_xcp ?
1554 			adev->gfx.num_xcc_per_xcp : 1));
1555 }
1556 
1557 static ssize_t amdgpu_gfx_get_current_compute_partition(struct device *dev,
1558 						struct device_attribute *addr,
1559 						char *buf)
1560 {
1561 	struct drm_device *ddev = dev_get_drvdata(dev);
1562 	struct amdgpu_device *adev = drm_to_adev(ddev);
1563 	int mode;
1564 
1565 	/* Only minimal precaution taken to reject requests while in reset.*/
1566 	if (amdgpu_in_reset(adev))
1567 		return -EPERM;
1568 
1569 	mode = amdgpu_xcp_query_partition_mode(adev->xcp_mgr,
1570 					       AMDGPU_XCP_FL_NONE);
1571 
1572 	return sysfs_emit(buf, "%s\n", amdgpu_gfx_compute_mode_desc(mode));
1573 }
1574 
1575 static ssize_t amdgpu_gfx_set_compute_partition(struct device *dev,
1576 						struct device_attribute *addr,
1577 						const char *buf, size_t count)
1578 {
1579 	struct drm_device *ddev = dev_get_drvdata(dev);
1580 	struct amdgpu_device *adev = drm_to_adev(ddev);
1581 	enum amdgpu_gfx_partition mode;
1582 	int ret = 0, num_xcc;
1583 
1584 	num_xcc = NUM_XCC(adev->gfx.xcc_mask);
1585 	if (num_xcc % 2 != 0)
1586 		return -EINVAL;
1587 
1588 	if (!strncasecmp("SPX", buf, strlen("SPX"))) {
1589 		mode = AMDGPU_SPX_PARTITION_MODE;
1590 	} else if (!strncasecmp("DPX", buf, strlen("DPX"))) {
1591 		/*
1592 		 * DPX mode needs AIDs to be in multiple of 2.
1593 		 * Each AID connects 2 XCCs.
1594 		 */
1595 		if (num_xcc%4)
1596 			return -EINVAL;
1597 		mode = AMDGPU_DPX_PARTITION_MODE;
1598 	} else if (!strncasecmp("TPX", buf, strlen("TPX"))) {
1599 		if (num_xcc != 6)
1600 			return -EINVAL;
1601 		mode = AMDGPU_TPX_PARTITION_MODE;
1602 	} else if (!strncasecmp("QPX", buf, strlen("QPX"))) {
1603 		if (num_xcc != 8)
1604 			return -EINVAL;
1605 		mode = AMDGPU_QPX_PARTITION_MODE;
1606 	} else if (!strncasecmp("CPX", buf, strlen("CPX"))) {
1607 		mode = AMDGPU_CPX_PARTITION_MODE;
1608 	} else {
1609 		return -EINVAL;
1610 	}
1611 
1612 	/* Don't allow a switch while under reset */
1613 	if (!down_read_trylock(&adev->reset_domain->sem))
1614 		return -EPERM;
1615 
1616 	ret = amdgpu_xcp_switch_partition_mode(adev->xcp_mgr, mode);
1617 
1618 	up_read(&adev->reset_domain->sem);
1619 
1620 	if (ret)
1621 		return ret;
1622 
1623 	return count;
1624 }
1625 
1626 static ssize_t compute_partition_mem_alloc_mode_show(struct device *dev,
1627 						struct device_attribute *addr,
1628 						char *buf)
1629 {
1630 	struct drm_device *ddev = dev_get_drvdata(dev);
1631 	struct amdgpu_device *adev = drm_to_adev(ddev);
1632 	int mode = adev->xcp_mgr->mem_alloc_mode;
1633 
1634 	return sysfs_emit(buf, "%s\n",
1635 			  amdgpu_gfx_compute_mem_alloc_mode_desc(mode));
1636 }
1637 
1638 
1639 static ssize_t compute_partition_mem_alloc_mode_store(struct device *dev,
1640 						struct device_attribute *addr,
1641 						const char *buf, size_t count)
1642 {
1643 	struct drm_device *ddev = dev_get_drvdata(dev);
1644 	struct amdgpu_device *adev = drm_to_adev(ddev);
1645 
1646 	if (!strncasecmp("CAPPING", buf, strlen("CAPPING")))
1647 		adev->xcp_mgr->mem_alloc_mode = AMDGPU_PARTITION_MEM_CAPPING_EVEN;
1648 	else if (!strncasecmp("ALL", buf, strlen("ALL")))
1649 		adev->xcp_mgr->mem_alloc_mode = AMDGPU_PARTITION_MEM_ALLOC_ALL;
1650 	else
1651 		return -EINVAL;
1652 
1653 	return count;
1654 }
1655 
1656 static const char *xcp_desc[] = {
1657 	[AMDGPU_SPX_PARTITION_MODE] = "SPX",
1658 	[AMDGPU_DPX_PARTITION_MODE] = "DPX",
1659 	[AMDGPU_TPX_PARTITION_MODE] = "TPX",
1660 	[AMDGPU_QPX_PARTITION_MODE] = "QPX",
1661 	[AMDGPU_CPX_PARTITION_MODE] = "CPX",
1662 };
1663 
1664 static ssize_t amdgpu_gfx_get_available_compute_partition(struct device *dev,
1665 						struct device_attribute *addr,
1666 						char *buf)
1667 {
1668 	struct drm_device *ddev = dev_get_drvdata(dev);
1669 	struct amdgpu_device *adev = drm_to_adev(ddev);
1670 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
1671 	int size = 0, mode;
1672 	char *sep = "";
1673 
1674 	if (!xcp_mgr || !xcp_mgr->avail_xcp_modes)
1675 		return sysfs_emit(buf, "Not supported\n");
1676 
1677 	for_each_inst(mode, xcp_mgr->avail_xcp_modes) {
1678 		size += sysfs_emit_at(buf, size, "%s%s", sep, xcp_desc[mode]);
1679 		sep = ", ";
1680 	}
1681 
1682 	size += sysfs_emit_at(buf, size, "\n");
1683 
1684 	return size;
1685 }
1686 
1687 static int amdgpu_gfx_run_cleaner_shader_job(struct amdgpu_ring *ring)
1688 {
1689 	struct amdgpu_device *adev = ring->adev;
1690 	struct drm_gpu_scheduler *sched = &ring->sched;
1691 	struct drm_sched_entity entity;
1692 	unsigned int ib_size_dw = 16;
1693 	static atomic_t counter;
1694 	struct dma_fence *f;
1695 	struct amdgpu_job *job;
1696 	struct amdgpu_ib *ib;
1697 	void *owner;
1698 	int r;
1699 
1700 	/* Initialize the scheduler entity */
1701 	r = drm_sched_entity_init(&entity, DRM_SCHED_PRIORITY_NORMAL,
1702 				  &sched, 1, NULL);
1703 	if (r) {
1704 		dev_err(adev->dev, "Failed setting up GFX kernel entity.\n");
1705 		goto err;
1706 	}
1707 
1708 	/*
1709 	 * Use some unique dummy value as the owner to make sure we execute
1710 	 * the cleaner shader on each submission. The value just need to change
1711 	 * for each submission and is otherwise meaningless.
1712 	 */
1713 	owner = (void *)(unsigned long)atomic_inc_return(&counter);
1714 
1715 	r = amdgpu_job_alloc_with_ib(ring->adev, &entity, owner,
1716 				     ib_size_dw * sizeof(uint32_t), 0, &job,
1717 				     AMDGPU_KERNEL_JOB_ID_CLEANER_SHADER);
1718 	if (r)
1719 		goto err;
1720 
1721 	job->enforce_isolation = true;
1722 	/* always run the cleaner shader */
1723 	job->run_cleaner_shader = true;
1724 
1725 	ib = &job->ibs[0];
1726 	memset32(ib->ptr, ring->funcs->nop, ib_size_dw);
1727 	ib->length_dw = ib_size_dw;
1728 
1729 	f = amdgpu_job_submit(job);
1730 
1731 	r = dma_fence_wait(f, false);
1732 	if (r)
1733 		goto err;
1734 
1735 	dma_fence_put(f);
1736 
1737 	/* Clean up the scheduler entity */
1738 	drm_sched_entity_destroy(&entity);
1739 	return 0;
1740 
1741 err:
1742 	return r;
1743 }
1744 
1745 static int amdgpu_gfx_run_cleaner_shader(struct amdgpu_device *adev, int xcp_id)
1746 {
1747 	int num_xcc = NUM_XCC(adev->gfx.xcc_mask);
1748 	struct amdgpu_ring *ring;
1749 	int num_xcc_to_clear;
1750 	int i, r, xcc_id;
1751 
1752 	if (adev->gfx.num_xcc_per_xcp)
1753 		num_xcc_to_clear = adev->gfx.num_xcc_per_xcp;
1754 	else
1755 		num_xcc_to_clear = 1;
1756 
1757 	for (xcc_id = 0; xcc_id < num_xcc; xcc_id++) {
1758 		for (i = 0; i < adev->gfx.num_compute_rings; i++) {
1759 			ring = &adev->gfx.compute_ring[i + xcc_id * adev->gfx.num_compute_rings];
1760 			if ((ring->xcp_id == xcp_id) && ring->sched.ready) {
1761 				r = amdgpu_gfx_run_cleaner_shader_job(ring);
1762 				if (r)
1763 					return r;
1764 				num_xcc_to_clear--;
1765 				break;
1766 			}
1767 		}
1768 	}
1769 
1770 	if (num_xcc_to_clear)
1771 		return -ENOENT;
1772 
1773 	return 0;
1774 }
1775 
1776 /**
1777  * amdgpu_gfx_set_run_cleaner_shader - Execute the AMDGPU GFX Cleaner Shader
1778  * @dev: The device structure
1779  * @attr: The device attribute structure
1780  * @buf: The buffer containing the input data
1781  * @count: The size of the input data
1782  *
1783  * Provides the sysfs interface to manually run a cleaner shader, which is
1784  * used to clear the GPU state between different tasks. Writing a value to the
1785  * 'run_cleaner_shader' sysfs file triggers the cleaner shader execution.
1786  * The value written corresponds to the partition index on multi-partition
1787  * devices. On single-partition devices, the value should be '0'.
1788  *
1789  * The cleaner shader clears the Local Data Store (LDS) and General Purpose
1790  * Registers (GPRs) to ensure data isolation between GPU workloads.
1791  *
1792  * Return: The number of bytes written to the sysfs file.
1793  */
1794 static ssize_t amdgpu_gfx_set_run_cleaner_shader(struct device *dev,
1795 						 struct device_attribute *attr,
1796 						 const char *buf,
1797 						 size_t count)
1798 {
1799 	struct drm_device *ddev = dev_get_drvdata(dev);
1800 	struct amdgpu_device *adev = drm_to_adev(ddev);
1801 	int ret;
1802 	long value;
1803 
1804 	if (amdgpu_in_reset(adev))
1805 		return -EPERM;
1806 	if (adev->in_suspend && !adev->in_runpm)
1807 		return -EPERM;
1808 
1809 	if (adev->gfx.disable_kq)
1810 		return -EPERM;
1811 
1812 	ret = kstrtol(buf, 0, &value);
1813 
1814 	if (ret)
1815 		return -EINVAL;
1816 
1817 	if (value < 0)
1818 		return -EINVAL;
1819 
1820 	if (adev->xcp_mgr) {
1821 		if (value >= adev->xcp_mgr->num_xcps)
1822 			return -EINVAL;
1823 	} else {
1824 		if (value > 1)
1825 			return -EINVAL;
1826 	}
1827 
1828 	ret = pm_runtime_get_sync(ddev->dev);
1829 	if (ret < 0) {
1830 		pm_runtime_put_autosuspend(ddev->dev);
1831 		return ret;
1832 	}
1833 
1834 	ret = amdgpu_gfx_run_cleaner_shader(adev, value);
1835 
1836 	pm_runtime_put_autosuspend(ddev->dev);
1837 
1838 	if (ret)
1839 		return ret;
1840 
1841 	return count;
1842 }
1843 
1844 /**
1845  * amdgpu_gfx_get_enforce_isolation - Query AMDGPU GFX Enforce Isolation Settings
1846  * @dev: The device structure
1847  * @attr: The device attribute structure
1848  * @buf: The buffer to store the output data
1849  *
1850  * Provides the sysfs read interface to get the current settings of the 'enforce_isolation'
1851  * feature for each GPU partition. Reading from the 'enforce_isolation'
1852  * sysfs file returns the isolation settings for all partitions, where '0'
1853  * indicates disabled, '1' indicates enabled, and '2' indicates enabled in legacy mode,
1854  * and '3' indicates enabled without cleaner shader.
1855  *
1856  * Return: The number of bytes read from the sysfs file.
1857  */
1858 static ssize_t amdgpu_gfx_get_enforce_isolation(struct device *dev,
1859 						struct device_attribute *attr,
1860 						char *buf)
1861 {
1862 	struct drm_device *ddev = dev_get_drvdata(dev);
1863 	struct amdgpu_device *adev = drm_to_adev(ddev);
1864 	int i;
1865 	ssize_t size = 0;
1866 
1867 	if (adev->xcp_mgr) {
1868 		for (i = 0; i < adev->xcp_mgr->num_xcps; i++) {
1869 			size += sysfs_emit_at(buf, size, "%u", adev->enforce_isolation[i]);
1870 			if (i < (adev->xcp_mgr->num_xcps - 1))
1871 				size += sysfs_emit_at(buf, size, " ");
1872 		}
1873 		buf[size++] = '\n';
1874 	} else {
1875 		size = sysfs_emit_at(buf, 0, "%u\n", adev->enforce_isolation[0]);
1876 	}
1877 
1878 	return size;
1879 }
1880 
1881 /**
1882  * amdgpu_gfx_set_enforce_isolation - Control AMDGPU GFX Enforce Isolation
1883  * @dev: The device structure
1884  * @attr: The device attribute structure
1885  * @buf: The buffer containing the input data
1886  * @count: The size of the input data
1887  *
1888  * This function allows control over the 'enforce_isolation' feature, which
1889  * serializes access to the graphics engine. Writing '0' to disable, '1' to
1890  * enable isolation with cleaner shader, '2' to enable legacy isolation without
1891  * cleaner shader, or '3' to enable process isolation without submitting the
1892  * cleaner shader to the 'enforce_isolation' sysfs file sets the isolation mode
1893  * for each partition. The input should specify the setting for all
1894  * partitions.
1895  *
1896  * Return: The number of bytes written to the sysfs file.
1897  */
1898 static ssize_t amdgpu_gfx_set_enforce_isolation(struct device *dev,
1899 						struct device_attribute *attr,
1900 						const char *buf, size_t count)
1901 {
1902 	struct drm_device *ddev = dev_get_drvdata(dev);
1903 	struct amdgpu_device *adev = drm_to_adev(ddev);
1904 	long partition_values[MAX_XCP] = {0};
1905 	int ret, i, num_partitions;
1906 	const char *input_buf = buf;
1907 
1908 	for (i = 0; i < (adev->xcp_mgr ? adev->xcp_mgr->num_xcps : 1); i++) {
1909 		ret = sscanf(input_buf, "%ld", &partition_values[i]);
1910 		if (ret <= 0)
1911 			break;
1912 
1913 		/* Move the pointer to the next value in the string */
1914 		input_buf = strchr(input_buf, ' ');
1915 		if (input_buf) {
1916 			input_buf++;
1917 		} else {
1918 			i++;
1919 			break;
1920 		}
1921 	}
1922 	num_partitions = i;
1923 
1924 	if (adev->xcp_mgr && num_partitions != adev->xcp_mgr->num_xcps)
1925 		return -EINVAL;
1926 
1927 	if (!adev->xcp_mgr && num_partitions != 1)
1928 		return -EINVAL;
1929 
1930 	for (i = 0; i < num_partitions; i++) {
1931 		if (partition_values[i] != 0 &&
1932 		    partition_values[i] != 1 &&
1933 		    partition_values[i] != 2 &&
1934 		    partition_values[i] != 3)
1935 			return -EINVAL;
1936 	}
1937 
1938 	mutex_lock(&adev->enforce_isolation_mutex);
1939 	for (i = 0; i < num_partitions; i++) {
1940 		switch (partition_values[i]) {
1941 		case 0:
1942 		default:
1943 			adev->enforce_isolation[i] = AMDGPU_ENFORCE_ISOLATION_DISABLE;
1944 			break;
1945 		case 1:
1946 			adev->enforce_isolation[i] =
1947 				AMDGPU_ENFORCE_ISOLATION_ENABLE;
1948 			break;
1949 		case 2:
1950 			adev->enforce_isolation[i] =
1951 				AMDGPU_ENFORCE_ISOLATION_ENABLE_LEGACY;
1952 			break;
1953 		case 3:
1954 			adev->enforce_isolation[i] =
1955 				AMDGPU_ENFORCE_ISOLATION_NO_CLEANER_SHADER;
1956 			break;
1957 		}
1958 	}
1959 	mutex_unlock(&adev->enforce_isolation_mutex);
1960 
1961 	amdgpu_mes_update_enforce_isolation(adev);
1962 
1963 	return count;
1964 }
1965 
1966 static ssize_t amdgpu_gfx_get_gfx_reset_mask(struct device *dev,
1967 						struct device_attribute *attr,
1968 						char *buf)
1969 {
1970 	struct drm_device *ddev = dev_get_drvdata(dev);
1971 	struct amdgpu_device *adev = drm_to_adev(ddev);
1972 
1973 	if (!adev)
1974 		return -ENODEV;
1975 
1976 	return amdgpu_show_reset_mask(buf, adev->gfx.gfx_supported_reset);
1977 }
1978 
1979 static ssize_t amdgpu_gfx_get_compute_reset_mask(struct device *dev,
1980 						struct device_attribute *attr,
1981 						char *buf)
1982 {
1983 	struct drm_device *ddev = dev_get_drvdata(dev);
1984 	struct amdgpu_device *adev = drm_to_adev(ddev);
1985 
1986 	if (!adev)
1987 		return -ENODEV;
1988 
1989 	return amdgpu_show_reset_mask(buf, adev->gfx.compute_supported_reset);
1990 }
1991 
1992 static int amdgpu_gfx_mes_reset_queue_start(struct amdgpu_ring *ring,
1993 					     unsigned int vmid,
1994 					     struct amdgpu_fence *timedout_fence,
1995 					     bool use_mmio)
1996 {
1997 	struct amdgpu_device *adev = ring->adev;
1998 	bool reinit_queue;
1999 	int r;
2000 
2001 	if ((ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE) &&
2002 	    adev->mes.compute_pipe_reset_enabled)
2003 		reinit_queue = true;
2004 	else if ((ring->funcs->type == AMDGPU_RING_TYPE_GFX) &&
2005 		 adev->mes.gfx_pipe_reset_enabled)
2006 		reinit_queue = true;
2007 	else
2008 		reinit_queue = use_mmio;
2009 
2010 	amdgpu_ring_reset_helper_begin(ring, timedout_fence);
2011 
2012 	r = amdgpu_mes_reset_legacy_queue(ring->adev, ring, vmid, use_mmio, 0);
2013 	if (r)
2014 		return r;
2015 
2016 	if (reinit_queue) {
2017 		r = amdgpu_mes_unmap_legacy_queue(adev, ring,
2018 						  RESET_QUEUES, 0, 0, 0);
2019 		if (r)
2020 			return r;
2021 		amdgpu_gfx_mqd_reset_restore(ring);
2022 
2023 		r = amdgpu_mes_map_legacy_queue(adev, ring, 0);
2024 		if (r) {
2025 			dev_err(adev->dev, "failed to remap kgq\n");
2026 			return r;
2027 		}
2028 	}
2029 	return 0;
2030 }
2031 
2032 int amdgpu_gfx_mes_reset_queue(struct amdgpu_ring *ring,
2033 			       unsigned int vmid,
2034 			       struct amdgpu_fence *timedout_fence,
2035 			       bool use_mmio)
2036 {
2037 	int r;
2038 
2039 	r = amdgpu_gfx_mes_reset_queue_start(ring, vmid, timedout_fence,
2040 					      use_mmio);
2041 	if (r)
2042 		return r;
2043 	return amdgpu_ring_reset_helper_end(ring, timedout_fence);
2044 }
2045 
2046 static DEVICE_ATTR(run_cleaner_shader, 0200,
2047 		   NULL, amdgpu_gfx_set_run_cleaner_shader);
2048 
2049 static DEVICE_ATTR(enforce_isolation, 0644,
2050 		   amdgpu_gfx_get_enforce_isolation,
2051 		   amdgpu_gfx_set_enforce_isolation);
2052 
2053 static DEVICE_ATTR(current_compute_partition, 0644,
2054 		   amdgpu_gfx_get_current_compute_partition,
2055 		   amdgpu_gfx_set_compute_partition);
2056 
2057 static DEVICE_ATTR(available_compute_partition, 0444,
2058 		   amdgpu_gfx_get_available_compute_partition, NULL);
2059 static DEVICE_ATTR(gfx_reset_mask, 0444,
2060 		   amdgpu_gfx_get_gfx_reset_mask, NULL);
2061 
2062 static DEVICE_ATTR(compute_reset_mask, 0444,
2063 		   amdgpu_gfx_get_compute_reset_mask, NULL);
2064 
2065 static DEVICE_ATTR(compute_partition_mem_alloc_mode, 0644,
2066 		   compute_partition_mem_alloc_mode_show,
2067 		   compute_partition_mem_alloc_mode_store);
2068 
2069 static int amdgpu_gfx_sysfs_xcp_init(struct amdgpu_device *adev)
2070 {
2071 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
2072 	bool xcp_switch_supported;
2073 	int r;
2074 
2075 	if (!xcp_mgr)
2076 		return 0;
2077 
2078 	xcp_switch_supported =
2079 		(xcp_mgr->funcs && xcp_mgr->funcs->switch_partition_mode);
2080 
2081 	if (!xcp_switch_supported)
2082 		dev_attr_current_compute_partition.attr.mode &=
2083 			~(S_IWUSR | S_IWGRP | S_IWOTH);
2084 
2085 	r = device_create_file(adev->dev, &dev_attr_current_compute_partition);
2086 	if (r)
2087 		return r;
2088 
2089 	r = device_create_file(adev->dev,
2090 			       &dev_attr_compute_partition_mem_alloc_mode);
2091 	if (r)
2092 		return r;
2093 
2094 	if (xcp_switch_supported)
2095 		r = device_create_file(adev->dev,
2096 				       &dev_attr_available_compute_partition);
2097 
2098 	return r;
2099 }
2100 
2101 static void amdgpu_gfx_sysfs_xcp_fini(struct amdgpu_device *adev)
2102 {
2103 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
2104 	bool xcp_switch_supported;
2105 
2106 	if (!xcp_mgr)
2107 		return;
2108 
2109 	xcp_switch_supported =
2110 		(xcp_mgr->funcs && xcp_mgr->funcs->switch_partition_mode);
2111 	device_remove_file(adev->dev, &dev_attr_current_compute_partition);
2112 
2113 	device_remove_file(adev->dev, &dev_attr_compute_partition_mem_alloc_mode);
2114 
2115 	if (xcp_switch_supported)
2116 		device_remove_file(adev->dev,
2117 				   &dev_attr_available_compute_partition);
2118 }
2119 
2120 static int amdgpu_gfx_sysfs_isolation_shader_init(struct amdgpu_device *adev)
2121 {
2122 	int r;
2123 
2124 	r = device_create_file(adev->dev, &dev_attr_enforce_isolation);
2125 	if (r)
2126 		return r;
2127 	if (adev->gfx.enable_cleaner_shader)
2128 		r = device_create_file(adev->dev, &dev_attr_run_cleaner_shader);
2129 
2130 	return r;
2131 }
2132 
2133 static void amdgpu_gfx_sysfs_isolation_shader_fini(struct amdgpu_device *adev)
2134 {
2135 	device_remove_file(adev->dev, &dev_attr_enforce_isolation);
2136 	if (adev->gfx.enable_cleaner_shader)
2137 		device_remove_file(adev->dev, &dev_attr_run_cleaner_shader);
2138 }
2139 
2140 static int amdgpu_gfx_sysfs_reset_mask_init(struct amdgpu_device *adev)
2141 {
2142 	int r = 0;
2143 
2144 	if (!amdgpu_gpu_recovery)
2145 		return r;
2146 
2147 	if (adev->gfx.num_gfx_rings) {
2148 		r = device_create_file(adev->dev, &dev_attr_gfx_reset_mask);
2149 		if (r)
2150 			return r;
2151 	}
2152 
2153 	if (adev->gfx.num_compute_rings) {
2154 		r = device_create_file(adev->dev, &dev_attr_compute_reset_mask);
2155 		if (r)
2156 			return r;
2157 	}
2158 
2159 	return r;
2160 }
2161 
2162 static void amdgpu_gfx_sysfs_reset_mask_fini(struct amdgpu_device *adev)
2163 {
2164 	if (!amdgpu_gpu_recovery)
2165 		return;
2166 
2167 	if (adev->gfx.num_gfx_rings)
2168 		device_remove_file(adev->dev, &dev_attr_gfx_reset_mask);
2169 
2170 	if (adev->gfx.num_compute_rings)
2171 		device_remove_file(adev->dev, &dev_attr_compute_reset_mask);
2172 }
2173 
2174 int amdgpu_gfx_sysfs_init(struct amdgpu_device *adev)
2175 {
2176 	int r;
2177 
2178 	r = amdgpu_gfx_sysfs_xcp_init(adev);
2179 	if (r) {
2180 		dev_err(adev->dev, "failed to create xcp sysfs files");
2181 		return r;
2182 	}
2183 
2184 	r = amdgpu_gfx_sysfs_isolation_shader_init(adev);
2185 	if (r)
2186 		dev_err(adev->dev, "failed to create isolation sysfs files");
2187 
2188 	r = amdgpu_gfx_sysfs_reset_mask_init(adev);
2189 	if (r)
2190 		dev_err(adev->dev, "failed to create reset mask sysfs files");
2191 
2192 	return r;
2193 }
2194 
2195 void amdgpu_gfx_sysfs_fini(struct amdgpu_device *adev)
2196 {
2197 	if (adev->dev->kobj.sd) {
2198 		amdgpu_gfx_sysfs_xcp_fini(adev);
2199 		amdgpu_gfx_sysfs_isolation_shader_fini(adev);
2200 		amdgpu_gfx_sysfs_reset_mask_fini(adev);
2201 	}
2202 }
2203 
2204 static void amdgpu_gfx_reset_start_compute_scheds(struct amdgpu_device *adev,
2205 						  struct amdgpu_ring *guilty_ring)
2206 {
2207 	struct amdgpu_ring *ring;
2208 	int i;
2209 
2210 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
2211 		ring = &adev->gfx.compute_ring[i];
2212 		if (ring == guilty_ring)
2213 			continue;
2214 		drm_sched_wqueue_start(&ring->sched);
2215 	}
2216 }
2217 
2218 static void amdgpu_gfx_reset_stop_compute_scheds(struct amdgpu_device *adev,
2219 						 struct amdgpu_ring *guilty_ring)
2220 {
2221 	struct amdgpu_ring *ring;
2222 	int i;
2223 
2224 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
2225 		ring = &adev->gfx.compute_ring[i];
2226 		if (ring == guilty_ring)
2227 			continue;
2228 		drm_sched_wqueue_stop(&ring->sched);
2229 	}
2230 }
2231 
2232 /*
2233  * Match the MES-reported hung doorbell against a compute ring and run
2234  * the reset. On hit, the matched ring and its guilty fence are returned
2235  * via *out_ring / *out_fence so the caller can defer reset end until
2236  * after MES has resumed all gangs.
2237  */
2238 static int amdgpu_gfx_reset_mes_kcq(struct amdgpu_device *adev,
2239 				    struct amdgpu_ring *guilty_ring,
2240 				    unsigned int db,
2241 				    struct amdgpu_ring **out_ring,
2242 				    struct amdgpu_fence **out_fence)
2243 {
2244 	bool use_mmio = adev->gfx.mec.use_mmio_for_reset;
2245 	struct amdgpu_fence *fence;
2246 	struct amdgpu_ring *ring;
2247 	int i, r;
2248 
2249 	*out_ring = NULL;
2250 	*out_fence = NULL;
2251 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
2252 		ring = &adev->gfx.compute_ring[i];
2253 		if (ring == guilty_ring)
2254 			continue;
2255 		if (ring->doorbell_index == db) {
2256 			fence = amdgpu_ring_find_guilty_fence(ring);
2257 			r = amdgpu_gfx_mes_reset_queue_start(ring, 0, fence,
2258 							      use_mmio);
2259 			if (r)
2260 				return r;
2261 			*out_ring = ring;
2262 			*out_fence = fence;
2263 			break;
2264 		}
2265 	}
2266 	return 0;
2267 }
2268 
2269 int amdgpu_gfx_reset_mes_compute(struct amdgpu_device *adev,
2270 				 struct amdgpu_ring *ring,
2271 				 struct amdgpu_fence *guilty_fence,
2272 				 struct amdgpu_usermode_queue *uq,
2273 				 unsigned int *hung_queue_count,
2274 				 void *faulty_queue_input)
2275 {
2276 	struct amdgpu_mes_hung_queue_hqd_info *hqd_info =
2277 		(struct amdgpu_mes_hung_queue_hqd_info *)
2278 		&adev->gfx.mec.mes_hung_db_array[adev->mes.hung_queue_hqd_info_offset];
2279 	int i, r, pipe, queue, queue_type;
2280 	unsigned int num_hung = 0;
2281 	bool use_mmio = adev->gfx.mec.use_mmio_for_reset;
2282 	struct mes_remove_queue_input *queue_input = (struct mes_remove_queue_input *)faulty_queue_input;
2283 	struct amdgpu_gfx_deferred_entry deferred_end[AMDGPU_MAX_COMPUTE_RINGS + 1];
2284 	int n_deferred = 0;
2285 	int ring_err;
2286 
2287 	guard(mutex)(&adev->gfx.mec.reset_mutex);
2288 	/* stop the drm schedulers for all compute queues */
2289 	amdgpu_gfx_reset_stop_compute_scheds(adev, ring);
2290 	/* suspend all will determine which queues are hung.
2291 	 * reset detect will return the array of bad queue doorbells
2292 	 */
2293 	r = amdgpu_mes_suspend(adev, 0);
2294 	/* if suspend all success, it should no hang queue */
2295 	if (!r)
2296 		/* always reset the KCQ/userq since we need to signal the fence
2297 		 * and we could be stuck in a loop which is preemptable.
2298 		 */
2299 		goto fence_reset;
2300 	r = amdgpu_mes_detect_and_reset_hung_queues(adev, AMDGPU_RING_TYPE_COMPUTE,
2301 						    true, &num_hung, adev->gfx.mec.mes_hung_db_array, 0);
2302 	if (r)
2303 		goto out;
2304 	if (hung_queue_count)
2305 		*hung_queue_count = num_hung;
2306 
2307 fence_reset:
2308 	/* reset the queue this came from if specified */
2309 	if (ring) {
2310 		r = amdgpu_gfx_mes_reset_queue_start(ring, 0, guilty_fence,
2311 						      use_mmio);
2312 		if (r)
2313 			goto out;
2314 		deferred_end[n_deferred].ring = ring;
2315 		deferred_end[n_deferred].fence = guilty_fence;
2316 		n_deferred++;
2317 	}
2318 	if (uq) {
2319 		r = mes_userq_reset(uq);
2320 		if (r)
2321 			goto out;
2322 	}
2323 	for (i = 0; i < num_hung; i++) {
2324 		struct amdgpu_ring *hr = NULL;
2325 		struct amdgpu_fence *hf = NULL;
2326 
2327 		pipe = hqd_info[i].pipe_index;
2328 		queue = hqd_info[i].queue_index;
2329 		queue_type = hqd_info[i].queue_type;
2330 
2331 		/* reset any KCQs */
2332 		r = amdgpu_gfx_reset_mes_kcq(adev, ring,
2333 					     adev->gfx.mec.mes_hung_db_array[i],
2334 					     &hr, &hf);
2335 		if (r)
2336 			goto out;
2337 		if (hr) {
2338 			deferred_end[n_deferred].ring = hr;
2339 			deferred_end[n_deferred].fence = hf;
2340 			n_deferred++;
2341 		}
2342 		/* reset any KFD queues */
2343 		r = amdgpu_amdkfd_reset_mes_queue(adev, 0, queue_type, pipe, queue,
2344 						  adev->gfx.mec.mes_hung_db_array[i]);
2345 		if (r)
2346 			goto out;
2347 		/* reset KGD user queues */
2348 		r = mes_userq_reset_queue(adev, uq, queue_type, pipe, queue,
2349 					  adev->gfx.mec.mes_hung_db_array[i]);
2350 		if (r)
2351 			goto out;
2352 	}
2353 
2354 	/* MES doesn't detect any hung queue but we have a known bad queue
2355 	 * and it is not KCQ
2356 	 */
2357 	if (!num_hung && queue_input && !ring) {
2358 		/* MES suspend_all is successful means this bad queue is
2359 		 * preempted successfuly. Remove it before resume all so it
2360 		 * doesn't get mapped back
2361 		 */
2362 		if (!down_read_trylock(&adev->reset_domain->sem)) {
2363 			r = -EIO;
2364 			goto out;
2365 		}
2366 		amdgpu_mes_lock(&adev->mes);
2367 		r = adev->mes.funcs->remove_hw_queue(&adev->mes, queue_input);
2368 		amdgpu_mes_unlock(&adev->mes);
2369 		up_read(&adev->reset_domain->sem);
2370 	}
2371 
2372 out:
2373 	/* resume all will enable the non-hung queues */
2374 	amdgpu_mes_resume(adev, 0);
2375 
2376 	/* Now CP is running again — replay backed-up commands and ring
2377 	 * doorbells on each reset queue.
2378 	 */
2379 	ring_err = r;
2380 	for (i = 0; i < n_deferred; i++) {
2381 		int er = amdgpu_ring_reset_helper_end(deferred_end[i].ring,
2382 						      deferred_end[i].fence);
2383 
2384 		if (er && !ring_err)
2385 			ring_err = er;
2386 	}
2387 
2388 	if (!ring_err)
2389 		amdgpu_gfx_reset_start_compute_scheds(adev, ring);
2390 
2391 	/* If this reset is triggered by non-KCQ, the KCQ result after resume must
2392 	 * not override the reset result; otherwise a false reset failure is returned
2393 	 * to the non-KCQ caller
2394 	 */
2395 	return ring ? ring_err : r;
2396 }
2397 
2398 int amdgpu_gfx_cleaner_shader_sw_init(struct amdgpu_device *adev,
2399 				      unsigned int cleaner_shader_size)
2400 {
2401 	if (!adev->gfx.enable_cleaner_shader)
2402 		return -EOPNOTSUPP;
2403 
2404 	return amdgpu_bo_create_kernel(adev, cleaner_shader_size, PAGE_SIZE,
2405 				       AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2406 				       &adev->gfx.cleaner_shader_obj,
2407 				       &adev->gfx.cleaner_shader_gpu_addr,
2408 				       (void **)&adev->gfx.cleaner_shader_cpu_ptr);
2409 }
2410 
2411 void amdgpu_gfx_cleaner_shader_sw_fini(struct amdgpu_device *adev)
2412 {
2413 	if (!adev->gfx.enable_cleaner_shader)
2414 		return;
2415 
2416 	amdgpu_bo_free_kernel(&adev->gfx.cleaner_shader_obj,
2417 			      &adev->gfx.cleaner_shader_gpu_addr,
2418 			      (void **)&adev->gfx.cleaner_shader_cpu_ptr);
2419 }
2420 
2421 void amdgpu_gfx_cleaner_shader_init(struct amdgpu_device *adev,
2422 				    unsigned int cleaner_shader_size,
2423 				    const void *cleaner_shader_ptr)
2424 {
2425 	if (!adev->gfx.enable_cleaner_shader)
2426 		return;
2427 
2428 	if (adev->gfx.cleaner_shader_cpu_ptr && cleaner_shader_ptr)
2429 		memcpy_toio(adev->gfx.cleaner_shader_cpu_ptr, cleaner_shader_ptr,
2430 			    cleaner_shader_size);
2431 }
2432 
2433 /**
2434  * amdgpu_gfx_kfd_sch_ctrl - Control the KFD scheduler from the KGD (Graphics Driver)
2435  * @adev: amdgpu_device pointer
2436  * @idx: Index of the scheduler to control
2437  * @enable: Whether to enable or disable the KFD scheduler
2438  *
2439  * This function is used to control the KFD (Kernel Fusion Driver) scheduler
2440  * from the KGD. It is part of the cleaner shader feature. This function plays
2441  * a key role in enforcing process isolation on the GPU.
2442  *
2443  * The function uses a reference count mechanism (kfd_sch_req_count) to keep
2444  * track of the number of requests to enable the KFD scheduler. When a request
2445  * to enable the KFD scheduler is made, the reference count is decremented.
2446  * When the reference count reaches zero, a delayed work is scheduled to
2447  * enforce isolation after a delay of GFX_SLICE_PERIOD.
2448  *
2449  * When a request to disable the KFD scheduler is made, the function first
2450  * checks if the reference count is zero. If it is, it cancels the delayed work
2451  * for enforcing isolation and checks if the KFD scheduler is active. If the
2452  * KFD scheduler is active, it sends a request to stop the KFD scheduler and
2453  * sets the KFD scheduler state to inactive. Then, it increments the reference
2454  * count.
2455  *
2456  * The function is synchronized using the kfd_sch_mutex to ensure that the KFD
2457  * scheduler state and reference count are updated atomically.
2458  *
2459  * Note: If the reference count is already zero when a request to enable the
2460  * KFD scheduler is made, it means there's an imbalance bug somewhere. The
2461  * function triggers a warning in this case.
2462  */
2463 static void amdgpu_gfx_kfd_sch_ctrl(struct amdgpu_device *adev, u32 idx,
2464 				    bool enable)
2465 {
2466 	mutex_lock(&adev->gfx.userq_sch_mutex);
2467 
2468 	if (enable) {
2469 		/* If the count is already 0, it means there's an imbalance bug somewhere.
2470 		 * Note that the bug may be in a different caller than the one which triggers the
2471 		 * WARN_ON_ONCE.
2472 		 */
2473 		if (WARN_ON_ONCE(adev->gfx.userq_sch_req_count[idx] == 0)) {
2474 			dev_err(adev->dev, "Attempted to enable KFD scheduler when reference count is already zero\n");
2475 			goto unlock;
2476 		}
2477 
2478 		adev->gfx.userq_sch_req_count[idx]--;
2479 
2480 		if (adev->gfx.userq_sch_req_count[idx] == 0 &&
2481 		    adev->gfx.userq_sch_inactive[idx]) {
2482 			schedule_delayed_work(&adev->gfx.enforce_isolation[idx].work,
2483 					      msecs_to_jiffies(adev->gfx.enforce_isolation_time[idx]));
2484 		}
2485 	} else {
2486 		if (adev->gfx.userq_sch_req_count[idx] == 0) {
2487 			cancel_delayed_work_sync(&adev->gfx.enforce_isolation[idx].work);
2488 			if (!adev->gfx.userq_sch_inactive[idx]) {
2489 				amdgpu_userq_stop_sched_for_enforce_isolation(adev, idx);
2490 				if (adev->kfd.init_complete)
2491 					amdgpu_amdkfd_stop_sched(adev, idx);
2492 				adev->gfx.userq_sch_inactive[idx] = true;
2493 			}
2494 		}
2495 
2496 		adev->gfx.userq_sch_req_count[idx]++;
2497 	}
2498 
2499 unlock:
2500 	mutex_unlock(&adev->gfx.userq_sch_mutex);
2501 }
2502 
2503 /**
2504  * amdgpu_gfx_enforce_isolation_handler - work handler for enforcing shader isolation
2505  *
2506  * @work: work_struct.
2507  *
2508  * This function is the work handler for enforcing shader isolation on AMD GPUs.
2509  * It counts the number of emitted fences for each GFX and compute ring. If there
2510  * are any fences, it schedules the `enforce_isolation_work` to be run after a
2511  * delay of `GFX_SLICE_PERIOD`. If there are no fences, it signals the Kernel Fusion
2512  * Driver (KFD) to resume the runqueue. The function is synchronized using the
2513  * `enforce_isolation_mutex`.
2514  */
2515 void amdgpu_gfx_enforce_isolation_handler(struct work_struct *work)
2516 {
2517 	struct amdgpu_isolation_work *isolation_work =
2518 		container_of(work, struct amdgpu_isolation_work, work.work);
2519 	struct amdgpu_device *adev = isolation_work->adev;
2520 	u32 i, idx, fences = 0;
2521 
2522 	if (isolation_work->xcp_id == AMDGPU_XCP_NO_PARTITION)
2523 		idx = 0;
2524 	else
2525 		idx = isolation_work->xcp_id;
2526 
2527 	if (idx >= MAX_XCP)
2528 		return;
2529 
2530 	mutex_lock(&adev->enforce_isolation_mutex);
2531 	for (i = 0; i < AMDGPU_MAX_GFX_RINGS; ++i) {
2532 		if (isolation_work->xcp_id == adev->gfx.gfx_ring[i].xcp_id)
2533 			fences += amdgpu_fence_count_emitted(&adev->gfx.gfx_ring[i]);
2534 	}
2535 	for (i = 0; i < (AMDGPU_MAX_COMPUTE_RINGS * AMDGPU_MAX_GC_INSTANCES); ++i) {
2536 		if (isolation_work->xcp_id == adev->gfx.compute_ring[i].xcp_id)
2537 			fences += amdgpu_fence_count_emitted(&adev->gfx.compute_ring[i]);
2538 	}
2539 	if (fences) {
2540 		/* we've already had our timeslice, so let's wrap this up */
2541 		schedule_delayed_work(&adev->gfx.enforce_isolation[idx].work,
2542 				      msecs_to_jiffies(1));
2543 	} else {
2544 		/* Tell KFD to resume the runqueue */
2545 		WARN_ON_ONCE(!adev->gfx.userq_sch_inactive[idx]);
2546 		WARN_ON_ONCE(adev->gfx.userq_sch_req_count[idx]);
2547 
2548 		amdgpu_userq_start_sched_for_enforce_isolation(adev, idx);
2549 		if (adev->kfd.init_complete)
2550 			amdgpu_amdkfd_start_sched(adev, idx);
2551 		adev->gfx.userq_sch_inactive[idx] = false;
2552 	}
2553 	mutex_unlock(&adev->enforce_isolation_mutex);
2554 }
2555 
2556 /**
2557  * amdgpu_gfx_enforce_isolation_wait_for_kfd - Manage KFD wait period for process isolation
2558  * @adev: amdgpu_device pointer
2559  * @idx: Index of the GPU partition
2560  *
2561  * When kernel submissions come in, the jobs are given a time slice and once
2562  * that time slice is up, if there are KFD user queues active, kernel
2563  * submissions are blocked until KFD has had its time slice. Once the KFD time
2564  * slice is up, KFD user queues are preempted and kernel submissions are
2565  * unblocked and allowed to run again.
2566  */
2567 static void
2568 amdgpu_gfx_enforce_isolation_wait_for_kfd(struct amdgpu_device *adev,
2569 					  u32 idx)
2570 {
2571 	unsigned long cjiffies;
2572 	bool wait = false;
2573 
2574 	mutex_lock(&adev->enforce_isolation_mutex);
2575 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2576 		/* set the initial values if nothing is set */
2577 		if (!adev->gfx.enforce_isolation_jiffies[idx]) {
2578 			adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2579 			adev->gfx.enforce_isolation_time[idx] =	GFX_SLICE_PERIOD_MS;
2580 		}
2581 		/* Make sure KFD gets a chance to run */
2582 		if (amdgpu_amdkfd_compute_active(adev, idx)) {
2583 			cjiffies = jiffies;
2584 			if (time_after(cjiffies, adev->gfx.enforce_isolation_jiffies[idx])) {
2585 				cjiffies -= adev->gfx.enforce_isolation_jiffies[idx];
2586 				if ((jiffies_to_msecs(cjiffies) >= GFX_SLICE_PERIOD_MS)) {
2587 					/* if our time is up, let KGD work drain before scheduling more */
2588 					wait = true;
2589 					/* reset the timer period */
2590 					adev->gfx.enforce_isolation_time[idx] =	GFX_SLICE_PERIOD_MS;
2591 				} else {
2592 					/* set the timer period to what's left in our time slice */
2593 					adev->gfx.enforce_isolation_time[idx] =
2594 						GFX_SLICE_PERIOD_MS - jiffies_to_msecs(cjiffies);
2595 				}
2596 			} else {
2597 				/* if jiffies wrap around we will just wait a little longer */
2598 				adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2599 			}
2600 		} else {
2601 			/* if there is no KFD work, then set the full slice period */
2602 			adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2603 			adev->gfx.enforce_isolation_time[idx] = GFX_SLICE_PERIOD_MS;
2604 		}
2605 	}
2606 	mutex_unlock(&adev->enforce_isolation_mutex);
2607 
2608 	if (wait)
2609 		msleep(GFX_SLICE_PERIOD_MS);
2610 }
2611 
2612 /**
2613  * amdgpu_gfx_enforce_isolation_ring_begin_use - Begin use of a ring with enforced isolation
2614  * @ring: Pointer to the amdgpu_ring structure
2615  *
2616  * Ring begin_use helper implementation for gfx which serializes access to the
2617  * gfx IP between kernel submission IOCTLs and KFD user queues when isolation
2618  * enforcement is enabled. The kernel submission IOCTLs and KFD user queues
2619  * each get a time slice when both are active.
2620  */
2621 void amdgpu_gfx_enforce_isolation_ring_begin_use(struct amdgpu_ring *ring)
2622 {
2623 	struct amdgpu_device *adev = ring->adev;
2624 	u32 idx;
2625 	bool sched_work = false;
2626 
2627 	if (!adev->gfx.enable_cleaner_shader)
2628 		return;
2629 
2630 	if (ring->xcp_id == AMDGPU_XCP_NO_PARTITION)
2631 		idx = 0;
2632 	else
2633 		idx = ring->xcp_id;
2634 
2635 	if (idx >= MAX_XCP)
2636 		return;
2637 
2638 	/* Don't submit more work until KFD has had some time */
2639 	amdgpu_gfx_enforce_isolation_wait_for_kfd(adev, idx);
2640 
2641 	mutex_lock(&adev->enforce_isolation_mutex);
2642 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2643 		if (adev->kfd.init_complete)
2644 			sched_work = true;
2645 	}
2646 	mutex_unlock(&adev->enforce_isolation_mutex);
2647 
2648 	if (sched_work)
2649 		amdgpu_gfx_kfd_sch_ctrl(adev, idx, false);
2650 }
2651 
2652 /**
2653  * amdgpu_gfx_enforce_isolation_ring_end_use - End use of a ring with enforced isolation
2654  * @ring: Pointer to the amdgpu_ring structure
2655  *
2656  * Ring end_use helper implementation for gfx which serializes access to the
2657  * gfx IP between kernel submission IOCTLs and KFD user queues when isolation
2658  * enforcement is enabled. The kernel submission IOCTLs and KFD user queues
2659  * each get a time slice when both are active.
2660  */
2661 void amdgpu_gfx_enforce_isolation_ring_end_use(struct amdgpu_ring *ring)
2662 {
2663 	struct amdgpu_device *adev = ring->adev;
2664 	u32 idx;
2665 	bool sched_work = false;
2666 
2667 	if (!adev->gfx.enable_cleaner_shader)
2668 		return;
2669 
2670 	if (ring->xcp_id == AMDGPU_XCP_NO_PARTITION)
2671 		idx = 0;
2672 	else
2673 		idx = ring->xcp_id;
2674 
2675 	if (idx >= MAX_XCP)
2676 		return;
2677 
2678 	mutex_lock(&adev->enforce_isolation_mutex);
2679 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2680 		if (adev->kfd.init_complete)
2681 			sched_work = true;
2682 	}
2683 	mutex_unlock(&adev->enforce_isolation_mutex);
2684 
2685 	if (sched_work)
2686 		amdgpu_gfx_kfd_sch_ctrl(adev, idx, true);
2687 }
2688 
2689 void amdgpu_gfx_profile_idle_work_handler(struct work_struct *work)
2690 {
2691 	struct amdgpu_device *adev =
2692 		container_of(work, struct amdgpu_device, gfx.idle_work.work);
2693 	enum PP_SMC_POWER_PROFILE profile;
2694 	u32 i, fences = 0;
2695 	int r;
2696 
2697 	if (adev->gfx.num_gfx_rings)
2698 		profile = PP_SMC_POWER_PROFILE_FULLSCREEN3D;
2699 	else
2700 		profile = PP_SMC_POWER_PROFILE_COMPUTE;
2701 
2702 	for (i = 0; i < AMDGPU_MAX_GFX_RINGS; ++i)
2703 		fences += amdgpu_fence_count_emitted(&adev->gfx.gfx_ring[i]);
2704 	for (i = 0; i < (AMDGPU_MAX_COMPUTE_RINGS * AMDGPU_MAX_GC_INSTANCES); ++i)
2705 		fences += amdgpu_fence_count_emitted(&adev->gfx.compute_ring[i]);
2706 	if (!fences && !atomic_read(&adev->gfx.total_submission_cnt)) {
2707 		mutex_lock(&adev->gfx.workload_profile_mutex);
2708 		if (adev->gfx.workload_profile_active) {
2709 			r = amdgpu_dpm_switch_power_profile(adev, profile, false);
2710 			if (r)
2711 				dev_warn(adev->dev, "(%d) failed to disable %s power profile mode\n", r,
2712 					 profile == PP_SMC_POWER_PROFILE_FULLSCREEN3D ?
2713 					 "fullscreen 3D" : "compute");
2714 			adev->gfx.workload_profile_active = false;
2715 		}
2716 		mutex_unlock(&adev->gfx.workload_profile_mutex);
2717 	} else {
2718 		schedule_delayed_work(&adev->gfx.idle_work, GFX_PROFILE_IDLE_TIMEOUT);
2719 	}
2720 }
2721 
2722 void amdgpu_gfx_profile_ring_begin_use(struct amdgpu_ring *ring)
2723 {
2724 	struct amdgpu_device *adev = ring->adev;
2725 	enum PP_SMC_POWER_PROFILE profile;
2726 	int r;
2727 
2728 	if (amdgpu_dpm_is_overdrive_enabled(adev))
2729 		return;
2730 
2731 	if (adev->gfx.num_gfx_rings)
2732 		profile = PP_SMC_POWER_PROFILE_FULLSCREEN3D;
2733 	else
2734 		profile = PP_SMC_POWER_PROFILE_COMPUTE;
2735 
2736 	if (!atomic_fetch_inc(&adev->gfx.total_submission_cnt))
2737 		cancel_delayed_work_sync(&adev->gfx.idle_work);
2738 
2739 	/* We can safely return early here because we've cancelled the
2740 	 * the delayed work so there is no one else to set it to false
2741 	 * and we don't care if someone else sets it to true.
2742 	 */
2743 	if (adev->gfx.workload_profile_active)
2744 		return;
2745 
2746 	mutex_lock(&adev->gfx.workload_profile_mutex);
2747 	if (!adev->gfx.workload_profile_active) {
2748 		r = amdgpu_dpm_switch_power_profile(adev, profile, true);
2749 		if (r)
2750 			dev_warn(adev->dev, "(%d) failed to disable %s power profile mode\n", r,
2751 				 profile == PP_SMC_POWER_PROFILE_FULLSCREEN3D ?
2752 				 "fullscreen 3D" : "compute");
2753 		adev->gfx.workload_profile_active = true;
2754 	}
2755 	mutex_unlock(&adev->gfx.workload_profile_mutex);
2756 }
2757 
2758 void amdgpu_gfx_profile_ring_end_use(struct amdgpu_ring *ring)
2759 {
2760 	struct amdgpu_device *adev = ring->adev;
2761 
2762 	if (amdgpu_dpm_is_overdrive_enabled(adev))
2763 		return;
2764 
2765 	if (atomic_dec_and_test(&ring->adev->gfx.total_submission_cnt))
2766 		schedule_delayed_work(&ring->adev->gfx.idle_work,
2767 				      GFX_PROFILE_IDLE_TIMEOUT);
2768 }
2769 
2770 /**
2771  * amdgpu_gfx_csb_preamble_start - Set CSB preamble start
2772  *
2773  * @buffer: This is an output variable that gets the PACKET3 preamble setup.
2774  *
2775  * Return:
2776  * return the latest index.
2777  */
2778 u32 amdgpu_gfx_csb_preamble_start(u32 *buffer)
2779 {
2780 	u32 count = 0;
2781 
2782 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
2783 	buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_BEGIN_CLEAR_STATE);
2784 
2785 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CONTEXT_CONTROL, 1));
2786 	buffer[count++] = cpu_to_le32(0x80000000);
2787 	buffer[count++] = cpu_to_le32(0x80000000);
2788 
2789 	return count;
2790 }
2791 
2792 /**
2793  * amdgpu_gfx_csb_data_parser - Parser CS data
2794  *
2795  * @adev: amdgpu_device pointer used to get the CS data and other gfx info.
2796  * @buffer: This is an output variable that gets the PACKET3 preamble end.
2797  * @count: Index to start set the preemble end.
2798  *
2799  * Return:
2800  * return the latest index.
2801  */
2802 u32 amdgpu_gfx_csb_data_parser(struct amdgpu_device *adev, u32 *buffer, u32 count)
2803 {
2804 	const struct cs_section_def *sect = NULL;
2805 	const struct cs_extent_def *ext = NULL;
2806 	u32 i;
2807 
2808 	for (sect = adev->gfx.rlc.cs_data; sect->section != NULL; ++sect) {
2809 		for (ext = sect->section; ext->extent != NULL; ++ext) {
2810 			if (sect->id == SECT_CONTEXT) {
2811 				buffer[count++] = cpu_to_le32(PACKET3(PACKET3_SET_CONTEXT_REG, ext->reg_count));
2812 				buffer[count++] = cpu_to_le32(ext->reg_index - PACKET3_SET_CONTEXT_REG_START);
2813 
2814 				for (i = 0; i < ext->reg_count; i++)
2815 					buffer[count++] = cpu_to_le32(ext->extent[i]);
2816 			}
2817 		}
2818 	}
2819 
2820 	return count;
2821 }
2822 
2823 /**
2824  * amdgpu_gfx_csb_preamble_end - Set CSB preamble end
2825  *
2826  * @buffer: This is an output variable that gets the PACKET3 preamble end.
2827  * @count: Index to start set the preemble end.
2828  */
2829 void amdgpu_gfx_csb_preamble_end(u32 *buffer, u32 count)
2830 {
2831 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
2832 	buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_END_CLEAR_STATE);
2833 
2834 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CLEAR_STATE, 0));
2835 	buffer[count++] = cpu_to_le32(0);
2836 }
2837 
2838 /*
2839  * debugfs for to enable/disable gfx job submission to specific core.
2840  */
2841 #if defined(CONFIG_DEBUG_FS)
2842 static int amdgpu_debugfs_gfx_sched_mask_set(void *data, u64 val)
2843 {
2844 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2845 	u32 i;
2846 	u64 mask = 0;
2847 	struct amdgpu_ring *ring;
2848 
2849 	if (!adev)
2850 		return -ENODEV;
2851 
2852 	mask = (1ULL << adev->gfx.num_gfx_rings) - 1;
2853 	if ((val & mask) == 0)
2854 		return -EINVAL;
2855 
2856 	for (i = 0; i < adev->gfx.num_gfx_rings; ++i) {
2857 		ring = &adev->gfx.gfx_ring[i];
2858 		if (val & (1 << i))
2859 			ring->sched.ready = true;
2860 		else
2861 			ring->sched.ready = false;
2862 	}
2863 	/* publish sched.ready flag update effective immediately across smp */
2864 	smp_rmb();
2865 	return 0;
2866 }
2867 
2868 static int amdgpu_debugfs_gfx_sched_mask_get(void *data, u64 *val)
2869 {
2870 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2871 	u32 i;
2872 	u64 mask = 0;
2873 	struct amdgpu_ring *ring;
2874 
2875 	if (!adev)
2876 		return -ENODEV;
2877 	for (i = 0; i < adev->gfx.num_gfx_rings; ++i) {
2878 		ring = &adev->gfx.gfx_ring[i];
2879 		if (ring->sched.ready)
2880 			mask |= 1ULL << i;
2881 	}
2882 
2883 	*val = mask;
2884 	return 0;
2885 }
2886 
2887 DEFINE_DEBUGFS_ATTRIBUTE(amdgpu_debugfs_gfx_sched_mask_fops,
2888 			 amdgpu_debugfs_gfx_sched_mask_get,
2889 			 amdgpu_debugfs_gfx_sched_mask_set, "%llx\n");
2890 
2891 #endif
2892 
2893 void amdgpu_debugfs_gfx_sched_mask_init(struct amdgpu_device *adev)
2894 {
2895 #if defined(CONFIG_DEBUG_FS)
2896 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2897 	struct dentry *root = minor->debugfs_root;
2898 	char name[32];
2899 
2900 	if (!(adev->gfx.num_gfx_rings > 1))
2901 		return;
2902 	sprintf(name, "amdgpu_gfx_sched_mask");
2903 	debugfs_create_file(name, 0600, root, adev,
2904 			    &amdgpu_debugfs_gfx_sched_mask_fops);
2905 #endif
2906 }
2907 
2908 /*
2909  * debugfs for to enable/disable compute job submission to specific core.
2910  */
2911 #if defined(CONFIG_DEBUG_FS)
2912 static int amdgpu_debugfs_compute_sched_mask_set(void *data, u64 val)
2913 {
2914 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2915 	u32 i;
2916 	u64 mask = 0;
2917 	struct amdgpu_ring *ring;
2918 
2919 	if (!adev)
2920 		return -ENODEV;
2921 
2922 	mask = (1ULL << adev->gfx.num_compute_rings) - 1;
2923 	if ((val & mask) == 0)
2924 		return -EINVAL;
2925 
2926 	for (i = 0; i < adev->gfx.num_compute_rings; ++i) {
2927 		ring = &adev->gfx.compute_ring[i];
2928 		if (val & (1 << i))
2929 			ring->sched.ready = true;
2930 		else
2931 			ring->sched.ready = false;
2932 	}
2933 
2934 	/* publish sched.ready flag update effective immediately across smp */
2935 	smp_rmb();
2936 	return 0;
2937 }
2938 
2939 static int amdgpu_debugfs_compute_sched_mask_get(void *data, u64 *val)
2940 {
2941 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2942 	u32 i;
2943 	u64 mask = 0;
2944 	struct amdgpu_ring *ring;
2945 
2946 	if (!adev)
2947 		return -ENODEV;
2948 	for (i = 0; i < adev->gfx.num_compute_rings; ++i) {
2949 		ring = &adev->gfx.compute_ring[i];
2950 		if (ring->sched.ready)
2951 			mask |= 1ULL << i;
2952 	}
2953 
2954 	*val = mask;
2955 	return 0;
2956 }
2957 
2958 DEFINE_DEBUGFS_ATTRIBUTE(amdgpu_debugfs_compute_sched_mask_fops,
2959 			 amdgpu_debugfs_compute_sched_mask_get,
2960 			 amdgpu_debugfs_compute_sched_mask_set, "%llx\n");
2961 
2962 #endif
2963 
2964 void amdgpu_debugfs_compute_sched_mask_init(struct amdgpu_device *adev)
2965 {
2966 #if defined(CONFIG_DEBUG_FS)
2967 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2968 	struct dentry *root = minor->debugfs_root;
2969 	char name[32];
2970 
2971 	if (!(adev->gfx.num_compute_rings > 1))
2972 		return;
2973 	sprintf(name, "amdgpu_compute_sched_mask");
2974 	debugfs_create_file(name, 0600, root, adev,
2975 			    &amdgpu_debugfs_compute_sched_mask_fops);
2976 #endif
2977 }
2978 
2979 int amdgpu_gfx_ring_preempt_ib(struct amdgpu_ring *ring)
2980 {
2981 	struct amdgpu_device *adev = ring->adev;
2982 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[0];
2983 	struct amdgpu_ring *kiq_ring = &kiq->ring;
2984 	unsigned long flags;
2985 	int i;
2986 
2987 	if (adev->enable_mes)
2988 		return -EINVAL;
2989 
2990 	if (!kiq->pmf || !kiq->pmf->kiq_unmap_queues)
2991 		return -EINVAL;
2992 
2993 	spin_lock_irqsave(&kiq->ring_lock, flags);
2994 
2995 	if (amdgpu_ring_alloc(kiq_ring, kiq->pmf->unmap_queues_size)) {
2996 		spin_unlock_irqrestore(&kiq->ring_lock, flags);
2997 		return -ENOMEM;
2998 	}
2999 
3000 	/* assert preemption condition */
3001 	amdgpu_ring_set_preempt_cond_exec(ring, false);
3002 
3003 	/* assert IB preemption, emit the trailing fence */
3004 	kiq->pmf->kiq_unmap_queues(kiq_ring, ring, PREEMPT_QUEUES_NO_UNMAP,
3005 					ring->trail_fence_gpu_addr,
3006 					++ring->trail_seq);
3007 	amdgpu_ring_commit(kiq_ring);
3008 
3009 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
3010 
3011 	/* poll the trailing fence */
3012 	for (i = 0; i < adev->usec_timeout; i++) {
3013 		if (ring->trail_seq ==
3014 			le32_to_cpu(*(ring->trail_fence_cpu_addr)))
3015 			break;
3016 		udelay(1);
3017 	}
3018 
3019 	/* deassert preemption condition */
3020     amdgpu_ring_set_preempt_cond_exec(ring, true);
3021 
3022 	if (i >= adev->usec_timeout) {
3023 		DRM_ERROR("ring %d failed to preempt ib\n", ring->idx);
3024 		return -EINVAL;
3025 	}
3026 
3027 	return 0;
3028 }
3029 
3030