xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gfx.c (revision 1c5e6cd8291f3e3c9f27b592a11bdb8408b2c64f)
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,
1717 				     AMDGPU_KERNEL_JOB_ID_CLEANER_SHADER,
1718 				     &job);
1719 	if (r)
1720 		goto err;
1721 
1722 	job->enforce_isolation = true;
1723 	/* always run the cleaner shader */
1724 	job->run_cleaner_shader = true;
1725 
1726 	ib = &job->ibs[0];
1727 	memset32(ib->ptr, ring->funcs->nop, ib_size_dw);
1728 	ib->length_dw = ib_size_dw;
1729 
1730 	f = amdgpu_job_submit(job);
1731 
1732 	r = dma_fence_wait(f, false);
1733 	if (r)
1734 		goto err;
1735 
1736 	dma_fence_put(f);
1737 
1738 	/* Clean up the scheduler entity */
1739 	drm_sched_entity_destroy(&entity);
1740 	return 0;
1741 
1742 err:
1743 	return r;
1744 }
1745 
1746 static int amdgpu_gfx_run_cleaner_shader(struct amdgpu_device *adev, int xcp_id)
1747 {
1748 	int num_xcc = NUM_XCC(adev->gfx.xcc_mask);
1749 	struct amdgpu_ring *ring;
1750 	int num_xcc_to_clear;
1751 	int i, r, xcc_id;
1752 
1753 	if (adev->gfx.num_xcc_per_xcp)
1754 		num_xcc_to_clear = adev->gfx.num_xcc_per_xcp;
1755 	else
1756 		num_xcc_to_clear = 1;
1757 
1758 	for (xcc_id = 0; xcc_id < num_xcc; xcc_id++) {
1759 		for (i = 0; i < adev->gfx.num_compute_rings; i++) {
1760 			ring = &adev->gfx.compute_ring[i + xcc_id * adev->gfx.num_compute_rings];
1761 			if ((ring->xcp_id == xcp_id) && ring->sched.ready) {
1762 				r = amdgpu_gfx_run_cleaner_shader_job(ring);
1763 				if (r)
1764 					return r;
1765 				num_xcc_to_clear--;
1766 				break;
1767 			}
1768 		}
1769 	}
1770 
1771 	if (num_xcc_to_clear)
1772 		return -ENOENT;
1773 
1774 	return 0;
1775 }
1776 
1777 /**
1778  * amdgpu_gfx_set_run_cleaner_shader - Execute the AMDGPU GFX Cleaner Shader
1779  * @dev: The device structure
1780  * @attr: The device attribute structure
1781  * @buf: The buffer containing the input data
1782  * @count: The size of the input data
1783  *
1784  * Provides the sysfs interface to manually run a cleaner shader, which is
1785  * used to clear the GPU state between different tasks. Writing a value to the
1786  * 'run_cleaner_shader' sysfs file triggers the cleaner shader execution.
1787  * The value written corresponds to the partition index on multi-partition
1788  * devices. On single-partition devices, the value should be '0'.
1789  *
1790  * The cleaner shader clears the Local Data Store (LDS) and General Purpose
1791  * Registers (GPRs) to ensure data isolation between GPU workloads.
1792  *
1793  * Return: The number of bytes written to the sysfs file.
1794  */
1795 static ssize_t amdgpu_gfx_set_run_cleaner_shader(struct device *dev,
1796 						 struct device_attribute *attr,
1797 						 const char *buf,
1798 						 size_t count)
1799 {
1800 	struct drm_device *ddev = dev_get_drvdata(dev);
1801 	struct amdgpu_device *adev = drm_to_adev(ddev);
1802 	int ret;
1803 	long value;
1804 
1805 	if (amdgpu_in_reset(adev))
1806 		return -EPERM;
1807 	if (adev->in_suspend && !adev->in_runpm)
1808 		return -EPERM;
1809 
1810 	if (adev->gfx.disable_kq)
1811 		return -EPERM;
1812 
1813 	ret = kstrtol(buf, 0, &value);
1814 
1815 	if (ret)
1816 		return -EINVAL;
1817 
1818 	if (value < 0)
1819 		return -EINVAL;
1820 
1821 	if (adev->xcp_mgr) {
1822 		if (value >= adev->xcp_mgr->num_xcps)
1823 			return -EINVAL;
1824 	} else {
1825 		if (value > 1)
1826 			return -EINVAL;
1827 	}
1828 
1829 	ret = pm_runtime_get_sync(ddev->dev);
1830 	if (ret < 0) {
1831 		pm_runtime_put_autosuspend(ddev->dev);
1832 		return ret;
1833 	}
1834 
1835 	ret = amdgpu_gfx_run_cleaner_shader(adev, value);
1836 
1837 	pm_runtime_put_autosuspend(ddev->dev);
1838 
1839 	if (ret)
1840 		return ret;
1841 
1842 	return count;
1843 }
1844 
1845 /**
1846  * amdgpu_gfx_get_enforce_isolation - Query AMDGPU GFX Enforce Isolation Settings
1847  * @dev: The device structure
1848  * @attr: The device attribute structure
1849  * @buf: The buffer to store the output data
1850  *
1851  * Provides the sysfs read interface to get the current settings of the 'enforce_isolation'
1852  * feature for each GPU partition. Reading from the 'enforce_isolation'
1853  * sysfs file returns the isolation settings for all partitions, where '0'
1854  * indicates disabled, '1' indicates enabled, and '2' indicates enabled in legacy mode,
1855  * and '3' indicates enabled without cleaner shader.
1856  *
1857  * Return: The number of bytes read from the sysfs file.
1858  */
1859 static ssize_t amdgpu_gfx_get_enforce_isolation(struct device *dev,
1860 						struct device_attribute *attr,
1861 						char *buf)
1862 {
1863 	struct drm_device *ddev = dev_get_drvdata(dev);
1864 	struct amdgpu_device *adev = drm_to_adev(ddev);
1865 	int i;
1866 	ssize_t size = 0;
1867 
1868 	if (adev->xcp_mgr) {
1869 		for (i = 0; i < adev->xcp_mgr->num_xcps; i++) {
1870 			size += sysfs_emit_at(buf, size, "%u", adev->enforce_isolation[i]);
1871 			if (i < (adev->xcp_mgr->num_xcps - 1))
1872 				size += sysfs_emit_at(buf, size, " ");
1873 		}
1874 		buf[size++] = '\n';
1875 	} else {
1876 		size = sysfs_emit_at(buf, 0, "%u\n", adev->enforce_isolation[0]);
1877 	}
1878 
1879 	return size;
1880 }
1881 
1882 /**
1883  * amdgpu_gfx_set_enforce_isolation - Control AMDGPU GFX Enforce Isolation
1884  * @dev: The device structure
1885  * @attr: The device attribute structure
1886  * @buf: The buffer containing the input data
1887  * @count: The size of the input data
1888  *
1889  * This function allows control over the 'enforce_isolation' feature, which
1890  * serializes access to the graphics engine. Writing '0' to disable, '1' to
1891  * enable isolation with cleaner shader, '2' to enable legacy isolation without
1892  * cleaner shader, or '3' to enable process isolation without submitting the
1893  * cleaner shader to the 'enforce_isolation' sysfs file sets the isolation mode
1894  * for each partition. The input should specify the setting for all
1895  * partitions.
1896  *
1897  * Return: The number of bytes written to the sysfs file.
1898  */
1899 static ssize_t amdgpu_gfx_set_enforce_isolation(struct device *dev,
1900 						struct device_attribute *attr,
1901 						const char *buf, size_t count)
1902 {
1903 	struct drm_device *ddev = dev_get_drvdata(dev);
1904 	struct amdgpu_device *adev = drm_to_adev(ddev);
1905 	long partition_values[MAX_XCP] = {0};
1906 	int ret, i, num_partitions;
1907 	const char *input_buf = buf;
1908 
1909 	for (i = 0; i < (adev->xcp_mgr ? adev->xcp_mgr->num_xcps : 1); i++) {
1910 		ret = sscanf(input_buf, "%ld", &partition_values[i]);
1911 		if (ret <= 0)
1912 			break;
1913 
1914 		/* Move the pointer to the next value in the string */
1915 		input_buf = strchr(input_buf, ' ');
1916 		if (input_buf) {
1917 			input_buf++;
1918 		} else {
1919 			i++;
1920 			break;
1921 		}
1922 	}
1923 	num_partitions = i;
1924 
1925 	if (adev->xcp_mgr && num_partitions != adev->xcp_mgr->num_xcps)
1926 		return -EINVAL;
1927 
1928 	if (!adev->xcp_mgr && num_partitions != 1)
1929 		return -EINVAL;
1930 
1931 	for (i = 0; i < num_partitions; i++) {
1932 		if (partition_values[i] != 0 &&
1933 		    partition_values[i] != 1 &&
1934 		    partition_values[i] != 2 &&
1935 		    partition_values[i] != 3)
1936 			return -EINVAL;
1937 	}
1938 
1939 	mutex_lock(&adev->enforce_isolation_mutex);
1940 	for (i = 0; i < num_partitions; i++) {
1941 		switch (partition_values[i]) {
1942 		case 0:
1943 		default:
1944 			adev->enforce_isolation[i] = AMDGPU_ENFORCE_ISOLATION_DISABLE;
1945 			break;
1946 		case 1:
1947 			adev->enforce_isolation[i] =
1948 				AMDGPU_ENFORCE_ISOLATION_ENABLE;
1949 			break;
1950 		case 2:
1951 			adev->enforce_isolation[i] =
1952 				AMDGPU_ENFORCE_ISOLATION_ENABLE_LEGACY;
1953 			break;
1954 		case 3:
1955 			adev->enforce_isolation[i] =
1956 				AMDGPU_ENFORCE_ISOLATION_NO_CLEANER_SHADER;
1957 			break;
1958 		}
1959 	}
1960 	mutex_unlock(&adev->enforce_isolation_mutex);
1961 
1962 	amdgpu_mes_update_enforce_isolation(adev);
1963 
1964 	return count;
1965 }
1966 
1967 static ssize_t amdgpu_gfx_get_gfx_reset_mask(struct device *dev,
1968 						struct device_attribute *attr,
1969 						char *buf)
1970 {
1971 	struct drm_device *ddev = dev_get_drvdata(dev);
1972 	struct amdgpu_device *adev = drm_to_adev(ddev);
1973 
1974 	if (!adev)
1975 		return -ENODEV;
1976 
1977 	return amdgpu_show_reset_mask(buf, adev->gfx.gfx_supported_reset);
1978 }
1979 
1980 static ssize_t amdgpu_gfx_get_compute_reset_mask(struct device *dev,
1981 						struct device_attribute *attr,
1982 						char *buf)
1983 {
1984 	struct drm_device *ddev = dev_get_drvdata(dev);
1985 	struct amdgpu_device *adev = drm_to_adev(ddev);
1986 
1987 	if (!adev)
1988 		return -ENODEV;
1989 
1990 	return amdgpu_show_reset_mask(buf, adev->gfx.compute_supported_reset);
1991 }
1992 
1993 static int amdgpu_gfx_mes_reset_queue_start(struct amdgpu_ring *ring,
1994 					     unsigned int vmid,
1995 					     struct amdgpu_fence *timedout_fence,
1996 					     bool use_mmio)
1997 {
1998 	struct amdgpu_device *adev = ring->adev;
1999 	bool reinit_queue;
2000 	int r;
2001 
2002 	if ((ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE) &&
2003 	    adev->mes.compute_pipe_reset_enabled)
2004 		reinit_queue = true;
2005 	else if ((ring->funcs->type == AMDGPU_RING_TYPE_GFX) &&
2006 		 adev->mes.gfx_pipe_reset_enabled)
2007 		reinit_queue = true;
2008 	else
2009 		reinit_queue = use_mmio;
2010 
2011 	amdgpu_ring_reset_helper_begin(ring, timedout_fence);
2012 
2013 	r = amdgpu_mes_reset_legacy_queue(ring->adev, ring, vmid, use_mmio, 0);
2014 	if (r)
2015 		return r;
2016 
2017 	if (reinit_queue) {
2018 		r = amdgpu_mes_unmap_legacy_queue(adev, ring,
2019 						  RESET_QUEUES, 0, 0, 0);
2020 		if (r)
2021 			return r;
2022 		amdgpu_gfx_mqd_reset_restore(ring);
2023 
2024 		r = amdgpu_mes_map_legacy_queue(adev, ring, 0);
2025 		if (r) {
2026 			dev_err(adev->dev, "failed to remap kgq\n");
2027 			return r;
2028 		}
2029 	}
2030 	return 0;
2031 }
2032 
2033 int amdgpu_gfx_mes_reset_queue(struct amdgpu_ring *ring,
2034 			       unsigned int vmid,
2035 			       struct amdgpu_fence *timedout_fence,
2036 			       bool use_mmio)
2037 {
2038 	int r;
2039 
2040 	r = amdgpu_gfx_mes_reset_queue_start(ring, vmid, timedout_fence,
2041 					      use_mmio);
2042 	if (r)
2043 		return r;
2044 	return amdgpu_ring_reset_helper_end(ring, timedout_fence);
2045 }
2046 
2047 static DEVICE_ATTR(run_cleaner_shader, 0200,
2048 		   NULL, amdgpu_gfx_set_run_cleaner_shader);
2049 
2050 static DEVICE_ATTR(enforce_isolation, 0644,
2051 		   amdgpu_gfx_get_enforce_isolation,
2052 		   amdgpu_gfx_set_enforce_isolation);
2053 
2054 static DEVICE_ATTR(current_compute_partition, 0644,
2055 		   amdgpu_gfx_get_current_compute_partition,
2056 		   amdgpu_gfx_set_compute_partition);
2057 
2058 static DEVICE_ATTR(available_compute_partition, 0444,
2059 		   amdgpu_gfx_get_available_compute_partition, NULL);
2060 static DEVICE_ATTR(gfx_reset_mask, 0444,
2061 		   amdgpu_gfx_get_gfx_reset_mask, NULL);
2062 
2063 static DEVICE_ATTR(compute_reset_mask, 0444,
2064 		   amdgpu_gfx_get_compute_reset_mask, NULL);
2065 
2066 static DEVICE_ATTR(compute_partition_mem_alloc_mode, 0644,
2067 		   compute_partition_mem_alloc_mode_show,
2068 		   compute_partition_mem_alloc_mode_store);
2069 
2070 static int amdgpu_gfx_sysfs_xcp_init(struct amdgpu_device *adev)
2071 {
2072 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
2073 	bool xcp_switch_supported;
2074 	int r;
2075 
2076 	if (!xcp_mgr)
2077 		return 0;
2078 
2079 	xcp_switch_supported =
2080 		(xcp_mgr->funcs && xcp_mgr->funcs->switch_partition_mode);
2081 
2082 	if (!xcp_switch_supported)
2083 		dev_attr_current_compute_partition.attr.mode &=
2084 			~(S_IWUSR | S_IWGRP | S_IWOTH);
2085 
2086 	r = device_create_file(adev->dev, &dev_attr_current_compute_partition);
2087 	if (r)
2088 		return r;
2089 
2090 	r = device_create_file(adev->dev,
2091 			       &dev_attr_compute_partition_mem_alloc_mode);
2092 	if (r)
2093 		return r;
2094 
2095 	if (xcp_switch_supported)
2096 		r = device_create_file(adev->dev,
2097 				       &dev_attr_available_compute_partition);
2098 
2099 	return r;
2100 }
2101 
2102 static void amdgpu_gfx_sysfs_xcp_fini(struct amdgpu_device *adev)
2103 {
2104 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
2105 	bool xcp_switch_supported;
2106 
2107 	if (!xcp_mgr)
2108 		return;
2109 
2110 	xcp_switch_supported =
2111 		(xcp_mgr->funcs && xcp_mgr->funcs->switch_partition_mode);
2112 	device_remove_file(adev->dev, &dev_attr_current_compute_partition);
2113 
2114 	device_remove_file(adev->dev, &dev_attr_compute_partition_mem_alloc_mode);
2115 
2116 	if (xcp_switch_supported)
2117 		device_remove_file(adev->dev,
2118 				   &dev_attr_available_compute_partition);
2119 }
2120 
2121 static int amdgpu_gfx_sysfs_isolation_shader_init(struct amdgpu_device *adev)
2122 {
2123 	int r;
2124 
2125 	r = device_create_file(adev->dev, &dev_attr_enforce_isolation);
2126 	if (r)
2127 		return r;
2128 	if (adev->gfx.enable_cleaner_shader)
2129 		r = device_create_file(adev->dev, &dev_attr_run_cleaner_shader);
2130 
2131 	return r;
2132 }
2133 
2134 static void amdgpu_gfx_sysfs_isolation_shader_fini(struct amdgpu_device *adev)
2135 {
2136 	device_remove_file(adev->dev, &dev_attr_enforce_isolation);
2137 	if (adev->gfx.enable_cleaner_shader)
2138 		device_remove_file(adev->dev, &dev_attr_run_cleaner_shader);
2139 }
2140 
2141 static int amdgpu_gfx_sysfs_reset_mask_init(struct amdgpu_device *adev)
2142 {
2143 	int r = 0;
2144 
2145 	if (!amdgpu_gpu_recovery)
2146 		return r;
2147 
2148 	if (adev->gfx.num_gfx_rings) {
2149 		r = device_create_file(adev->dev, &dev_attr_gfx_reset_mask);
2150 		if (r)
2151 			return r;
2152 	}
2153 
2154 	if (adev->gfx.num_compute_rings) {
2155 		r = device_create_file(adev->dev, &dev_attr_compute_reset_mask);
2156 		if (r)
2157 			return r;
2158 	}
2159 
2160 	return r;
2161 }
2162 
2163 static void amdgpu_gfx_sysfs_reset_mask_fini(struct amdgpu_device *adev)
2164 {
2165 	if (!amdgpu_gpu_recovery)
2166 		return;
2167 
2168 	if (adev->gfx.num_gfx_rings)
2169 		device_remove_file(adev->dev, &dev_attr_gfx_reset_mask);
2170 
2171 	if (adev->gfx.num_compute_rings)
2172 		device_remove_file(adev->dev, &dev_attr_compute_reset_mask);
2173 }
2174 
2175 int amdgpu_gfx_sysfs_init(struct amdgpu_device *adev)
2176 {
2177 	int r;
2178 
2179 	r = amdgpu_gfx_sysfs_xcp_init(adev);
2180 	if (r) {
2181 		dev_err(adev->dev, "failed to create xcp sysfs files");
2182 		return r;
2183 	}
2184 
2185 	r = amdgpu_gfx_sysfs_isolation_shader_init(adev);
2186 	if (r)
2187 		dev_err(adev->dev, "failed to create isolation sysfs files");
2188 
2189 	r = amdgpu_gfx_sysfs_reset_mask_init(adev);
2190 	if (r)
2191 		dev_err(adev->dev, "failed to create reset mask sysfs files");
2192 
2193 	return r;
2194 }
2195 
2196 void amdgpu_gfx_sysfs_fini(struct amdgpu_device *adev)
2197 {
2198 	if (adev->dev->kobj.sd) {
2199 		amdgpu_gfx_sysfs_xcp_fini(adev);
2200 		amdgpu_gfx_sysfs_isolation_shader_fini(adev);
2201 		amdgpu_gfx_sysfs_reset_mask_fini(adev);
2202 	}
2203 }
2204 
2205 static void amdgpu_gfx_reset_start_compute_scheds(struct amdgpu_device *adev,
2206 						  struct amdgpu_ring *guilty_ring)
2207 {
2208 	struct amdgpu_ring *ring;
2209 	int i;
2210 
2211 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
2212 		ring = &adev->gfx.compute_ring[i];
2213 		if (ring == guilty_ring)
2214 			continue;
2215 		drm_sched_wqueue_start(&ring->sched);
2216 	}
2217 }
2218 
2219 static void amdgpu_gfx_reset_stop_compute_scheds(struct amdgpu_device *adev,
2220 						 struct amdgpu_ring *guilty_ring)
2221 {
2222 	struct amdgpu_ring *ring;
2223 	int i;
2224 
2225 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
2226 		ring = &adev->gfx.compute_ring[i];
2227 		if (ring == guilty_ring)
2228 			continue;
2229 		drm_sched_wqueue_stop(&ring->sched);
2230 	}
2231 }
2232 
2233 /*
2234  * Match the MES-reported hung doorbell against a compute ring and run
2235  * the reset. On hit, the matched ring and its guilty fence are returned
2236  * via *out_ring / *out_fence so the caller can defer reset end until
2237  * after MES has resumed all gangs.
2238  */
2239 static int amdgpu_gfx_reset_mes_kcq(struct amdgpu_device *adev,
2240 				    struct amdgpu_ring *guilty_ring,
2241 				    unsigned int db,
2242 				    struct amdgpu_ring **out_ring,
2243 				    struct amdgpu_fence **out_fence)
2244 {
2245 	bool use_mmio = adev->gfx.mec.use_mmio_for_reset;
2246 	struct amdgpu_fence *fence;
2247 	struct amdgpu_ring *ring;
2248 	int i, r;
2249 
2250 	*out_ring = NULL;
2251 	*out_fence = NULL;
2252 	for (i = 0; i < adev->gfx.num_compute_rings; i++) {
2253 		ring = &adev->gfx.compute_ring[i];
2254 		if (ring == guilty_ring)
2255 			continue;
2256 		if (ring->doorbell_index == db) {
2257 			fence = amdgpu_ring_find_guilty_fence(ring);
2258 			r = amdgpu_gfx_mes_reset_queue_start(ring, 0, fence,
2259 							      use_mmio);
2260 			if (r)
2261 				return r;
2262 			*out_ring = ring;
2263 			*out_fence = fence;
2264 			break;
2265 		}
2266 	}
2267 	return 0;
2268 }
2269 
2270 int amdgpu_gfx_reset_mes_compute(struct amdgpu_device *adev,
2271 				 struct amdgpu_ring *ring,
2272 				 struct amdgpu_fence *guilty_fence,
2273 				 struct amdgpu_usermode_queue *uq,
2274 				 unsigned int *hung_queue_count,
2275 				 void *faulty_queue_input)
2276 {
2277 	struct amdgpu_mes_hung_queue_hqd_info *hqd_info =
2278 		(struct amdgpu_mes_hung_queue_hqd_info *)
2279 		&adev->gfx.mec.mes_hung_db_array[adev->mes.hung_queue_hqd_info_offset];
2280 	int i, r, pipe, queue, queue_type;
2281 	unsigned int num_hung = 0;
2282 	bool use_mmio = adev->gfx.mec.use_mmio_for_reset;
2283 	struct mes_remove_queue_input *queue_input = (struct mes_remove_queue_input *)faulty_queue_input;
2284 	struct amdgpu_gfx_deferred_entry deferred_end[AMDGPU_MAX_COMPUTE_RINGS + 1];
2285 	int n_deferred = 0;
2286 	int ring_err;
2287 
2288 	guard(mutex)(&adev->gfx.mec.reset_mutex);
2289 	/* stop the drm schedulers for all compute queues */
2290 	amdgpu_gfx_reset_stop_compute_scheds(adev, ring);
2291 	/* suspend all will determine which queues are hung.
2292 	 * reset detect will return the array of bad queue doorbells
2293 	 */
2294 	r = amdgpu_mes_suspend(adev, 0);
2295 	/* if suspend all success, it should no hang queue */
2296 	if (!r)
2297 		/* always reset the KCQ/userq since we need to signal the fence
2298 		 * and we could be stuck in a loop which is preemptable.
2299 		 */
2300 		goto fence_reset;
2301 	r = amdgpu_mes_detect_and_reset_hung_queues(adev, AMDGPU_RING_TYPE_COMPUTE,
2302 						    true, &num_hung, adev->gfx.mec.mes_hung_db_array, 0);
2303 	if (r)
2304 		goto out;
2305 	if (hung_queue_count)
2306 		*hung_queue_count = num_hung;
2307 
2308 fence_reset:
2309 	/* reset the queue this came from if specified */
2310 	if (ring) {
2311 		r = amdgpu_gfx_mes_reset_queue_start(ring, 0, guilty_fence,
2312 						      use_mmio);
2313 		if (r)
2314 			goto out;
2315 		deferred_end[n_deferred].ring = ring;
2316 		deferred_end[n_deferred].fence = guilty_fence;
2317 		n_deferred++;
2318 	}
2319 	if (uq) {
2320 		r = mes_userq_reset(uq);
2321 		if (r)
2322 			goto out;
2323 	}
2324 	for (i = 0; i < num_hung; i++) {
2325 		struct amdgpu_ring *hr = NULL;
2326 		struct amdgpu_fence *hf = NULL;
2327 
2328 		pipe = hqd_info[i].pipe_index;
2329 		queue = hqd_info[i].queue_index;
2330 		queue_type = hqd_info[i].queue_type;
2331 
2332 		/* reset any KCQs */
2333 		r = amdgpu_gfx_reset_mes_kcq(adev, ring,
2334 					     adev->gfx.mec.mes_hung_db_array[i],
2335 					     &hr, &hf);
2336 		if (r)
2337 			goto out;
2338 		if (hr) {
2339 			deferred_end[n_deferred].ring = hr;
2340 			deferred_end[n_deferred].fence = hf;
2341 			n_deferred++;
2342 		}
2343 		/* reset any KFD queues */
2344 		r = amdgpu_amdkfd_reset_mes_queue(adev, 0, queue_type, pipe, queue,
2345 						  adev->gfx.mec.mes_hung_db_array[i]);
2346 		if (r)
2347 			goto out;
2348 		/* reset KGD user queues */
2349 		r = mes_userq_reset_queue(adev, uq, queue_type, pipe, queue,
2350 					  adev->gfx.mec.mes_hung_db_array[i]);
2351 		if (r)
2352 			goto out;
2353 	}
2354 
2355 	/* MES doesn't detect any hung queue but we have a known bad queue
2356 	 * and it is not KCQ
2357 	 */
2358 	if (!num_hung && queue_input && !ring) {
2359 		/* MES suspend_all is successful means this bad queue is
2360 		 * preempted successfuly. Remove it before resume all so it
2361 		 * doesn't get mapped back
2362 		 */
2363 		if (!down_read_trylock(&adev->reset_domain->sem)) {
2364 			r = -EIO;
2365 			goto out;
2366 		}
2367 		amdgpu_mes_lock(&adev->mes);
2368 		r = adev->mes.funcs->remove_hw_queue(&adev->mes, queue_input);
2369 		amdgpu_mes_unlock(&adev->mes);
2370 		up_read(&adev->reset_domain->sem);
2371 	}
2372 
2373 out:
2374 	/* resume all will enable the non-hung queues */
2375 	amdgpu_mes_resume(adev, 0);
2376 
2377 	/* Now CP is running again — replay backed-up commands and ring
2378 	 * doorbells on each reset queue.
2379 	 */
2380 	ring_err = r;
2381 	for (i = 0; i < n_deferred; i++) {
2382 		int er = amdgpu_ring_reset_helper_end(deferred_end[i].ring,
2383 						      deferred_end[i].fence);
2384 
2385 		if (er && !ring_err)
2386 			ring_err = er;
2387 	}
2388 
2389 	if (!ring_err)
2390 		amdgpu_gfx_reset_start_compute_scheds(adev, ring);
2391 
2392 	/* If this reset is triggered by non-KCQ, the KCQ result after resume must
2393 	 * not override the reset result; otherwise a false reset failure is returned
2394 	 * to the non-KCQ caller
2395 	 */
2396 	return ring ? ring_err : r;
2397 }
2398 
2399 int amdgpu_gfx_cleaner_shader_sw_init(struct amdgpu_device *adev,
2400 				      unsigned int cleaner_shader_size)
2401 {
2402 	if (!adev->gfx.enable_cleaner_shader)
2403 		return -EOPNOTSUPP;
2404 
2405 	return amdgpu_bo_create_kernel(adev, cleaner_shader_size, PAGE_SIZE,
2406 				       AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2407 				       &adev->gfx.cleaner_shader_obj,
2408 				       &adev->gfx.cleaner_shader_gpu_addr,
2409 				       (void **)&adev->gfx.cleaner_shader_cpu_ptr);
2410 }
2411 
2412 void amdgpu_gfx_cleaner_shader_sw_fini(struct amdgpu_device *adev)
2413 {
2414 	if (!adev->gfx.enable_cleaner_shader)
2415 		return;
2416 
2417 	amdgpu_bo_free_kernel(&adev->gfx.cleaner_shader_obj,
2418 			      &adev->gfx.cleaner_shader_gpu_addr,
2419 			      (void **)&adev->gfx.cleaner_shader_cpu_ptr);
2420 }
2421 
2422 void amdgpu_gfx_cleaner_shader_init(struct amdgpu_device *adev,
2423 				    unsigned int cleaner_shader_size,
2424 				    const void *cleaner_shader_ptr)
2425 {
2426 	if (!adev->gfx.enable_cleaner_shader)
2427 		return;
2428 
2429 	if (adev->gfx.cleaner_shader_cpu_ptr && cleaner_shader_ptr)
2430 		memcpy_toio(adev->gfx.cleaner_shader_cpu_ptr, cleaner_shader_ptr,
2431 			    cleaner_shader_size);
2432 }
2433 
2434 /**
2435  * amdgpu_gfx_kfd_sch_ctrl - Control the KFD scheduler from the KGD (Graphics Driver)
2436  * @adev: amdgpu_device pointer
2437  * @idx: Index of the scheduler to control
2438  * @enable: Whether to enable or disable the KFD scheduler
2439  *
2440  * This function is used to control the KFD (Kernel Fusion Driver) scheduler
2441  * from the KGD. It is part of the cleaner shader feature. This function plays
2442  * a key role in enforcing process isolation on the GPU.
2443  *
2444  * The function uses a reference count mechanism (kfd_sch_req_count) to keep
2445  * track of the number of requests to enable the KFD scheduler. When a request
2446  * to enable the KFD scheduler is made, the reference count is decremented.
2447  * When the reference count reaches zero, a delayed work is scheduled to
2448  * enforce isolation after a delay of GFX_SLICE_PERIOD.
2449  *
2450  * When a request to disable the KFD scheduler is made, the function first
2451  * checks if the reference count is zero. If it is, it cancels the delayed work
2452  * for enforcing isolation and checks if the KFD scheduler is active. If the
2453  * KFD scheduler is active, it sends a request to stop the KFD scheduler and
2454  * sets the KFD scheduler state to inactive. Then, it increments the reference
2455  * count.
2456  *
2457  * The function is synchronized using the kfd_sch_mutex to ensure that the KFD
2458  * scheduler state and reference count are updated atomically.
2459  *
2460  * Note: If the reference count is already zero when a request to enable the
2461  * KFD scheduler is made, it means there's an imbalance bug somewhere. The
2462  * function triggers a warning in this case.
2463  */
2464 static void amdgpu_gfx_kfd_sch_ctrl(struct amdgpu_device *adev, u32 idx,
2465 				    bool enable)
2466 {
2467 	mutex_lock(&adev->gfx.userq_sch_mutex);
2468 
2469 	if (enable) {
2470 		/* If the count is already 0, it means there's an imbalance bug somewhere.
2471 		 * Note that the bug may be in a different caller than the one which triggers the
2472 		 * WARN_ON_ONCE.
2473 		 */
2474 		if (WARN_ON_ONCE(adev->gfx.userq_sch_req_count[idx] == 0)) {
2475 			dev_err(adev->dev, "Attempted to enable KFD scheduler when reference count is already zero\n");
2476 			goto unlock;
2477 		}
2478 
2479 		adev->gfx.userq_sch_req_count[idx]--;
2480 
2481 		if (adev->gfx.userq_sch_req_count[idx] == 0 &&
2482 		    adev->gfx.userq_sch_inactive[idx]) {
2483 			schedule_delayed_work(&adev->gfx.enforce_isolation[idx].work,
2484 					      msecs_to_jiffies(adev->gfx.enforce_isolation_time[idx]));
2485 		}
2486 	} else {
2487 		if (adev->gfx.userq_sch_req_count[idx] == 0) {
2488 			cancel_delayed_work_sync(&adev->gfx.enforce_isolation[idx].work);
2489 			if (!adev->gfx.userq_sch_inactive[idx]) {
2490 				amdgpu_userq_stop_sched_for_enforce_isolation(adev, idx);
2491 				if (adev->kfd.init_complete)
2492 					amdgpu_amdkfd_stop_sched(adev, idx);
2493 				adev->gfx.userq_sch_inactive[idx] = true;
2494 			}
2495 		}
2496 
2497 		adev->gfx.userq_sch_req_count[idx]++;
2498 	}
2499 
2500 unlock:
2501 	mutex_unlock(&adev->gfx.userq_sch_mutex);
2502 }
2503 
2504 /**
2505  * amdgpu_gfx_enforce_isolation_handler - work handler for enforcing shader isolation
2506  *
2507  * @work: work_struct.
2508  *
2509  * This function is the work handler for enforcing shader isolation on AMD GPUs.
2510  * It counts the number of emitted fences for each GFX and compute ring. If there
2511  * are any fences, it schedules the `enforce_isolation_work` to be run after a
2512  * delay of `GFX_SLICE_PERIOD`. If there are no fences, it signals the Kernel Fusion
2513  * Driver (KFD) to resume the runqueue. The function is synchronized using the
2514  * `enforce_isolation_mutex`.
2515  */
2516 void amdgpu_gfx_enforce_isolation_handler(struct work_struct *work)
2517 {
2518 	struct amdgpu_isolation_work *isolation_work =
2519 		container_of(work, struct amdgpu_isolation_work, work.work);
2520 	struct amdgpu_device *adev = isolation_work->adev;
2521 	u32 i, idx, fences = 0;
2522 
2523 	if (isolation_work->xcp_id == AMDGPU_XCP_NO_PARTITION)
2524 		idx = 0;
2525 	else
2526 		idx = isolation_work->xcp_id;
2527 
2528 	if (idx >= MAX_XCP)
2529 		return;
2530 
2531 	mutex_lock(&adev->enforce_isolation_mutex);
2532 	for (i = 0; i < AMDGPU_MAX_GFX_RINGS; ++i) {
2533 		if (isolation_work->xcp_id == adev->gfx.gfx_ring[i].xcp_id)
2534 			fences += amdgpu_fence_count_emitted(&adev->gfx.gfx_ring[i]);
2535 	}
2536 	for (i = 0; i < (AMDGPU_MAX_COMPUTE_RINGS * AMDGPU_MAX_GC_INSTANCES); ++i) {
2537 		if (isolation_work->xcp_id == adev->gfx.compute_ring[i].xcp_id)
2538 			fences += amdgpu_fence_count_emitted(&adev->gfx.compute_ring[i]);
2539 	}
2540 	if (fences) {
2541 		/* we've already had our timeslice, so let's wrap this up */
2542 		schedule_delayed_work(&adev->gfx.enforce_isolation[idx].work,
2543 				      msecs_to_jiffies(1));
2544 	} else {
2545 		/* Tell KFD to resume the runqueue */
2546 		WARN_ON_ONCE(!adev->gfx.userq_sch_inactive[idx]);
2547 		WARN_ON_ONCE(adev->gfx.userq_sch_req_count[idx]);
2548 
2549 		amdgpu_userq_start_sched_for_enforce_isolation(adev, idx);
2550 		if (adev->kfd.init_complete)
2551 			amdgpu_amdkfd_start_sched(adev, idx);
2552 		adev->gfx.userq_sch_inactive[idx] = false;
2553 	}
2554 	mutex_unlock(&adev->enforce_isolation_mutex);
2555 }
2556 
2557 /**
2558  * amdgpu_gfx_enforce_isolation_wait_for_kfd - Manage KFD wait period for process isolation
2559  * @adev: amdgpu_device pointer
2560  * @idx: Index of the GPU partition
2561  *
2562  * When kernel submissions come in, the jobs are given a time slice and once
2563  * that time slice is up, if there are KFD user queues active, kernel
2564  * submissions are blocked until KFD has had its time slice. Once the KFD time
2565  * slice is up, KFD user queues are preempted and kernel submissions are
2566  * unblocked and allowed to run again.
2567  */
2568 static void
2569 amdgpu_gfx_enforce_isolation_wait_for_kfd(struct amdgpu_device *adev,
2570 					  u32 idx)
2571 {
2572 	unsigned long cjiffies;
2573 	bool wait = false;
2574 
2575 	mutex_lock(&adev->enforce_isolation_mutex);
2576 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2577 		/* set the initial values if nothing is set */
2578 		if (!adev->gfx.enforce_isolation_jiffies[idx]) {
2579 			adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2580 			adev->gfx.enforce_isolation_time[idx] =	GFX_SLICE_PERIOD_MS;
2581 		}
2582 		/* Make sure KFD gets a chance to run */
2583 		if (amdgpu_amdkfd_compute_active(adev, idx)) {
2584 			cjiffies = jiffies;
2585 			if (time_after(cjiffies, adev->gfx.enforce_isolation_jiffies[idx])) {
2586 				cjiffies -= adev->gfx.enforce_isolation_jiffies[idx];
2587 				if ((jiffies_to_msecs(cjiffies) >= GFX_SLICE_PERIOD_MS)) {
2588 					/* if our time is up, let KGD work drain before scheduling more */
2589 					wait = true;
2590 					/* reset the timer period */
2591 					adev->gfx.enforce_isolation_time[idx] =	GFX_SLICE_PERIOD_MS;
2592 				} else {
2593 					/* set the timer period to what's left in our time slice */
2594 					adev->gfx.enforce_isolation_time[idx] =
2595 						GFX_SLICE_PERIOD_MS - jiffies_to_msecs(cjiffies);
2596 				}
2597 			} else {
2598 				/* if jiffies wrap around we will just wait a little longer */
2599 				adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2600 			}
2601 		} else {
2602 			/* if there is no KFD work, then set the full slice period */
2603 			adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2604 			adev->gfx.enforce_isolation_time[idx] = GFX_SLICE_PERIOD_MS;
2605 		}
2606 	}
2607 	mutex_unlock(&adev->enforce_isolation_mutex);
2608 
2609 	if (wait)
2610 		msleep(GFX_SLICE_PERIOD_MS);
2611 }
2612 
2613 /**
2614  * amdgpu_gfx_enforce_isolation_ring_begin_use - Begin use of a ring with enforced isolation
2615  * @ring: Pointer to the amdgpu_ring structure
2616  *
2617  * Ring begin_use helper implementation for gfx which serializes access to the
2618  * gfx IP between kernel submission IOCTLs and KFD user queues when isolation
2619  * enforcement is enabled. The kernel submission IOCTLs and KFD user queues
2620  * each get a time slice when both are active.
2621  */
2622 void amdgpu_gfx_enforce_isolation_ring_begin_use(struct amdgpu_ring *ring)
2623 {
2624 	struct amdgpu_device *adev = ring->adev;
2625 	u32 idx;
2626 	bool sched_work = false;
2627 
2628 	if (!adev->gfx.enable_cleaner_shader)
2629 		return;
2630 
2631 	if (ring->xcp_id == AMDGPU_XCP_NO_PARTITION)
2632 		idx = 0;
2633 	else
2634 		idx = ring->xcp_id;
2635 
2636 	if (idx >= MAX_XCP)
2637 		return;
2638 
2639 	/* Don't submit more work until KFD has had some time */
2640 	amdgpu_gfx_enforce_isolation_wait_for_kfd(adev, idx);
2641 
2642 	mutex_lock(&adev->enforce_isolation_mutex);
2643 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2644 		if (adev->kfd.init_complete)
2645 			sched_work = true;
2646 	}
2647 	mutex_unlock(&adev->enforce_isolation_mutex);
2648 
2649 	if (sched_work)
2650 		amdgpu_gfx_kfd_sch_ctrl(adev, idx, false);
2651 }
2652 
2653 /**
2654  * amdgpu_gfx_enforce_isolation_ring_end_use - End use of a ring with enforced isolation
2655  * @ring: Pointer to the amdgpu_ring structure
2656  *
2657  * Ring end_use helper implementation for gfx which serializes access to the
2658  * gfx IP between kernel submission IOCTLs and KFD user queues when isolation
2659  * enforcement is enabled. The kernel submission IOCTLs and KFD user queues
2660  * each get a time slice when both are active.
2661  */
2662 void amdgpu_gfx_enforce_isolation_ring_end_use(struct amdgpu_ring *ring)
2663 {
2664 	struct amdgpu_device *adev = ring->adev;
2665 	u32 idx;
2666 	bool sched_work = false;
2667 
2668 	if (!adev->gfx.enable_cleaner_shader)
2669 		return;
2670 
2671 	if (ring->xcp_id == AMDGPU_XCP_NO_PARTITION)
2672 		idx = 0;
2673 	else
2674 		idx = ring->xcp_id;
2675 
2676 	if (idx >= MAX_XCP)
2677 		return;
2678 
2679 	mutex_lock(&adev->enforce_isolation_mutex);
2680 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2681 		if (adev->kfd.init_complete)
2682 			sched_work = true;
2683 	}
2684 	mutex_unlock(&adev->enforce_isolation_mutex);
2685 
2686 	if (sched_work)
2687 		amdgpu_gfx_kfd_sch_ctrl(adev, idx, true);
2688 }
2689 
2690 void amdgpu_gfx_profile_idle_work_handler(struct work_struct *work)
2691 {
2692 	struct amdgpu_device *adev =
2693 		container_of(work, struct amdgpu_device, gfx.idle_work.work);
2694 	enum PP_SMC_POWER_PROFILE profile;
2695 	u32 i, fences = 0;
2696 	int r;
2697 
2698 	if (adev->gfx.num_gfx_rings)
2699 		profile = PP_SMC_POWER_PROFILE_FULLSCREEN3D;
2700 	else
2701 		profile = PP_SMC_POWER_PROFILE_COMPUTE;
2702 
2703 	for (i = 0; i < AMDGPU_MAX_GFX_RINGS; ++i)
2704 		fences += amdgpu_fence_count_emitted(&adev->gfx.gfx_ring[i]);
2705 	for (i = 0; i < (AMDGPU_MAX_COMPUTE_RINGS * AMDGPU_MAX_GC_INSTANCES); ++i)
2706 		fences += amdgpu_fence_count_emitted(&adev->gfx.compute_ring[i]);
2707 	if (!fences && !atomic_read(&adev->gfx.total_submission_cnt)) {
2708 		mutex_lock(&adev->gfx.workload_profile_mutex);
2709 		if (adev->gfx.workload_profile_active) {
2710 			r = amdgpu_dpm_switch_power_profile(adev, profile, false);
2711 			if (r)
2712 				dev_warn(adev->dev, "(%d) failed to disable %s power profile mode\n", r,
2713 					 profile == PP_SMC_POWER_PROFILE_FULLSCREEN3D ?
2714 					 "fullscreen 3D" : "compute");
2715 			adev->gfx.workload_profile_active = false;
2716 		}
2717 		mutex_unlock(&adev->gfx.workload_profile_mutex);
2718 	} else {
2719 		schedule_delayed_work(&adev->gfx.idle_work, GFX_PROFILE_IDLE_TIMEOUT);
2720 	}
2721 }
2722 
2723 void amdgpu_gfx_profile_ring_begin_use(struct amdgpu_ring *ring)
2724 {
2725 	struct amdgpu_device *adev = ring->adev;
2726 	enum PP_SMC_POWER_PROFILE profile;
2727 	int r;
2728 
2729 	if (amdgpu_dpm_is_overdrive_enabled(adev))
2730 		return;
2731 
2732 	if (adev->gfx.num_gfx_rings)
2733 		profile = PP_SMC_POWER_PROFILE_FULLSCREEN3D;
2734 	else
2735 		profile = PP_SMC_POWER_PROFILE_COMPUTE;
2736 
2737 	if (!atomic_fetch_inc(&adev->gfx.total_submission_cnt))
2738 		cancel_delayed_work_sync(&adev->gfx.idle_work);
2739 
2740 	/* We can safely return early here because we've cancelled the
2741 	 * the delayed work so there is no one else to set it to false
2742 	 * and we don't care if someone else sets it to true.
2743 	 */
2744 	if (adev->gfx.workload_profile_active)
2745 		return;
2746 
2747 	mutex_lock(&adev->gfx.workload_profile_mutex);
2748 	if (!adev->gfx.workload_profile_active) {
2749 		r = amdgpu_dpm_switch_power_profile(adev, profile, true);
2750 		if (r)
2751 			dev_warn(adev->dev, "(%d) failed to disable %s power profile mode\n", r,
2752 				 profile == PP_SMC_POWER_PROFILE_FULLSCREEN3D ?
2753 				 "fullscreen 3D" : "compute");
2754 		adev->gfx.workload_profile_active = true;
2755 	}
2756 	mutex_unlock(&adev->gfx.workload_profile_mutex);
2757 }
2758 
2759 void amdgpu_gfx_profile_ring_end_use(struct amdgpu_ring *ring)
2760 {
2761 	struct amdgpu_device *adev = ring->adev;
2762 
2763 	if (amdgpu_dpm_is_overdrive_enabled(adev))
2764 		return;
2765 
2766 	if (atomic_dec_and_test(&ring->adev->gfx.total_submission_cnt))
2767 		schedule_delayed_work(&ring->adev->gfx.idle_work,
2768 				      GFX_PROFILE_IDLE_TIMEOUT);
2769 }
2770 
2771 /**
2772  * amdgpu_gfx_csb_preamble_start - Set CSB preamble start
2773  *
2774  * @buffer: This is an output variable that gets the PACKET3 preamble setup.
2775  *
2776  * Return:
2777  * return the latest index.
2778  */
2779 u32 amdgpu_gfx_csb_preamble_start(u32 *buffer)
2780 {
2781 	u32 count = 0;
2782 
2783 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
2784 	buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_BEGIN_CLEAR_STATE);
2785 
2786 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CONTEXT_CONTROL, 1));
2787 	buffer[count++] = cpu_to_le32(0x80000000);
2788 	buffer[count++] = cpu_to_le32(0x80000000);
2789 
2790 	return count;
2791 }
2792 
2793 /**
2794  * amdgpu_gfx_csb_data_parser - Parser CS data
2795  *
2796  * @adev: amdgpu_device pointer used to get the CS data and other gfx info.
2797  * @buffer: This is an output variable that gets the PACKET3 preamble end.
2798  * @count: Index to start set the preemble end.
2799  *
2800  * Return:
2801  * return the latest index.
2802  */
2803 u32 amdgpu_gfx_csb_data_parser(struct amdgpu_device *adev, u32 *buffer, u32 count)
2804 {
2805 	const struct cs_section_def *sect = NULL;
2806 	const struct cs_extent_def *ext = NULL;
2807 	u32 i;
2808 
2809 	for (sect = adev->gfx.rlc.cs_data; sect->section != NULL; ++sect) {
2810 		for (ext = sect->section; ext->extent != NULL; ++ext) {
2811 			if (sect->id == SECT_CONTEXT) {
2812 				buffer[count++] = cpu_to_le32(PACKET3(PACKET3_SET_CONTEXT_REG, ext->reg_count));
2813 				buffer[count++] = cpu_to_le32(ext->reg_index - PACKET3_SET_CONTEXT_REG_START);
2814 
2815 				for (i = 0; i < ext->reg_count; i++)
2816 					buffer[count++] = cpu_to_le32(ext->extent[i]);
2817 			}
2818 		}
2819 	}
2820 
2821 	return count;
2822 }
2823 
2824 /**
2825  * amdgpu_gfx_csb_preamble_end - Set CSB preamble end
2826  *
2827  * @buffer: This is an output variable that gets the PACKET3 preamble end.
2828  * @count: Index to start set the preemble end.
2829  */
2830 void amdgpu_gfx_csb_preamble_end(u32 *buffer, u32 count)
2831 {
2832 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
2833 	buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_END_CLEAR_STATE);
2834 
2835 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CLEAR_STATE, 0));
2836 	buffer[count++] = cpu_to_le32(0);
2837 }
2838 
2839 /*
2840  * debugfs for to enable/disable gfx job submission to specific core.
2841  */
2842 #if defined(CONFIG_DEBUG_FS)
2843 static int amdgpu_debugfs_gfx_sched_mask_set(void *data, u64 val)
2844 {
2845 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2846 	u32 i;
2847 	u64 mask = 0;
2848 	struct amdgpu_ring *ring;
2849 
2850 	if (!adev)
2851 		return -ENODEV;
2852 
2853 	mask = (1ULL << adev->gfx.num_gfx_rings) - 1;
2854 	if ((val & mask) == 0)
2855 		return -EINVAL;
2856 
2857 	for (i = 0; i < adev->gfx.num_gfx_rings; ++i) {
2858 		ring = &adev->gfx.gfx_ring[i];
2859 		if (val & (1 << i))
2860 			ring->sched.ready = true;
2861 		else
2862 			ring->sched.ready = false;
2863 	}
2864 	/* publish sched.ready flag update effective immediately across smp */
2865 	smp_rmb();
2866 	return 0;
2867 }
2868 
2869 static int amdgpu_debugfs_gfx_sched_mask_get(void *data, u64 *val)
2870 {
2871 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2872 	u32 i;
2873 	u64 mask = 0;
2874 	struct amdgpu_ring *ring;
2875 
2876 	if (!adev)
2877 		return -ENODEV;
2878 	for (i = 0; i < adev->gfx.num_gfx_rings; ++i) {
2879 		ring = &adev->gfx.gfx_ring[i];
2880 		if (ring->sched.ready)
2881 			mask |= 1ULL << i;
2882 	}
2883 
2884 	*val = mask;
2885 	return 0;
2886 }
2887 
2888 DEFINE_DEBUGFS_ATTRIBUTE(amdgpu_debugfs_gfx_sched_mask_fops,
2889 			 amdgpu_debugfs_gfx_sched_mask_get,
2890 			 amdgpu_debugfs_gfx_sched_mask_set, "%llx\n");
2891 
2892 #endif
2893 
2894 void amdgpu_debugfs_gfx_sched_mask_init(struct amdgpu_device *adev)
2895 {
2896 #if defined(CONFIG_DEBUG_FS)
2897 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2898 	struct dentry *root = minor->debugfs_root;
2899 	char name[32];
2900 
2901 	if (!(adev->gfx.num_gfx_rings > 1))
2902 		return;
2903 	sprintf(name, "amdgpu_gfx_sched_mask");
2904 	debugfs_create_file(name, 0600, root, adev,
2905 			    &amdgpu_debugfs_gfx_sched_mask_fops);
2906 #endif
2907 }
2908 
2909 /*
2910  * debugfs for to enable/disable compute job submission to specific core.
2911  */
2912 #if defined(CONFIG_DEBUG_FS)
2913 static int amdgpu_debugfs_compute_sched_mask_set(void *data, u64 val)
2914 {
2915 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2916 	u32 i;
2917 	u64 mask = 0;
2918 	struct amdgpu_ring *ring;
2919 
2920 	if (!adev)
2921 		return -ENODEV;
2922 
2923 	mask = (1ULL << adev->gfx.num_compute_rings) - 1;
2924 	if ((val & mask) == 0)
2925 		return -EINVAL;
2926 
2927 	for (i = 0; i < adev->gfx.num_compute_rings; ++i) {
2928 		ring = &adev->gfx.compute_ring[i];
2929 		if (val & (1 << i))
2930 			ring->sched.ready = true;
2931 		else
2932 			ring->sched.ready = false;
2933 	}
2934 
2935 	/* publish sched.ready flag update effective immediately across smp */
2936 	smp_rmb();
2937 	return 0;
2938 }
2939 
2940 static int amdgpu_debugfs_compute_sched_mask_get(void *data, u64 *val)
2941 {
2942 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2943 	u32 i;
2944 	u64 mask = 0;
2945 	struct amdgpu_ring *ring;
2946 
2947 	if (!adev)
2948 		return -ENODEV;
2949 	for (i = 0; i < adev->gfx.num_compute_rings; ++i) {
2950 		ring = &adev->gfx.compute_ring[i];
2951 		if (ring->sched.ready)
2952 			mask |= 1ULL << i;
2953 	}
2954 
2955 	*val = mask;
2956 	return 0;
2957 }
2958 
2959 DEFINE_DEBUGFS_ATTRIBUTE(amdgpu_debugfs_compute_sched_mask_fops,
2960 			 amdgpu_debugfs_compute_sched_mask_get,
2961 			 amdgpu_debugfs_compute_sched_mask_set, "%llx\n");
2962 
2963 #endif
2964 
2965 void amdgpu_debugfs_compute_sched_mask_init(struct amdgpu_device *adev)
2966 {
2967 #if defined(CONFIG_DEBUG_FS)
2968 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2969 	struct dentry *root = minor->debugfs_root;
2970 	char name[32];
2971 
2972 	if (!(adev->gfx.num_compute_rings > 1))
2973 		return;
2974 	sprintf(name, "amdgpu_compute_sched_mask");
2975 	debugfs_create_file(name, 0600, root, adev,
2976 			    &amdgpu_debugfs_compute_sched_mask_fops);
2977 #endif
2978 }
2979 
2980 int amdgpu_gfx_ring_preempt_ib(struct amdgpu_ring *ring)
2981 {
2982 	struct amdgpu_device *adev = ring->adev;
2983 	struct amdgpu_kiq *kiq = &adev->gfx.kiq[0];
2984 	struct amdgpu_ring *kiq_ring = &kiq->ring;
2985 	unsigned long flags;
2986 	int i;
2987 
2988 	if (adev->enable_mes)
2989 		return -EINVAL;
2990 
2991 	if (!kiq->pmf || !kiq->pmf->kiq_unmap_queues)
2992 		return -EINVAL;
2993 
2994 	spin_lock_irqsave(&kiq->ring_lock, flags);
2995 
2996 	if (amdgpu_ring_alloc(kiq_ring, kiq->pmf->unmap_queues_size)) {
2997 		spin_unlock_irqrestore(&kiq->ring_lock, flags);
2998 		return -ENOMEM;
2999 	}
3000 
3001 	/* assert preemption condition */
3002 	amdgpu_ring_set_preempt_cond_exec(ring, false);
3003 
3004 	/* assert IB preemption, emit the trailing fence */
3005 	kiq->pmf->kiq_unmap_queues(kiq_ring, ring, PREEMPT_QUEUES_NO_UNMAP,
3006 					ring->trail_fence_gpu_addr,
3007 					++ring->trail_seq);
3008 	amdgpu_ring_commit(kiq_ring);
3009 
3010 	spin_unlock_irqrestore(&kiq->ring_lock, flags);
3011 
3012 	/* poll the trailing fence */
3013 	for (i = 0; i < adev->usec_timeout; i++) {
3014 		if (ring->trail_seq ==
3015 			le32_to_cpu(*(ring->trail_fence_cpu_addr)))
3016 			break;
3017 		udelay(1);
3018 	}
3019 
3020 	/* deassert preemption condition */
3021     amdgpu_ring_set_preempt_cond_exec(ring, true);
3022 
3023 	if (i >= adev->usec_timeout) {
3024 		DRM_ERROR("ring %d failed to preempt ib\n", ring->idx);
3025 		return -EINVAL;
3026 	}
3027 
3028 	return 0;
3029 }
3030 
3031