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