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