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