xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gfx.c (revision 592c5b80110d5e9e50873b5364818cb6f401e26d)
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 	if (!amdgpu_in_reset(adev))
1302 		dev_err(adev->dev, "failed to flush HDP via KIQ\n");
1303 	return r < 0 ? r : -EIO;
1304 }
1305 
1306 int amdgpu_gfx_get_num_kcq(struct amdgpu_device *adev)
1307 {
1308 	if (amdgpu_num_kcq == -1) {
1309 		return 8;
1310 	} else if (amdgpu_num_kcq > 8 || amdgpu_num_kcq < 0) {
1311 		dev_warn(adev->dev, "set kernel compute queue number to 8 due to invalid parameter provided by user\n");
1312 		return 8;
1313 	}
1314 	return amdgpu_num_kcq;
1315 }
1316 
1317 void amdgpu_gfx_cp_init_microcode(struct amdgpu_device *adev,
1318 				  uint32_t ucode_id)
1319 {
1320 	const struct gfx_firmware_header_v1_0 *cp_hdr;
1321 	const struct gfx_firmware_header_v2_0 *cp_hdr_v2_0;
1322 	struct amdgpu_firmware_info *info = NULL;
1323 	const struct firmware *ucode_fw;
1324 	unsigned int fw_size;
1325 
1326 	switch (ucode_id) {
1327 	case AMDGPU_UCODE_ID_CP_PFP:
1328 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1329 			adev->gfx.pfp_fw->data;
1330 		adev->gfx.pfp_fw_version =
1331 			le32_to_cpu(cp_hdr->header.ucode_version);
1332 		adev->gfx.pfp_feature_version =
1333 			le32_to_cpu(cp_hdr->ucode_feature_version);
1334 		ucode_fw = adev->gfx.pfp_fw;
1335 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes);
1336 		break;
1337 	case AMDGPU_UCODE_ID_CP_RS64_PFP:
1338 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1339 			adev->gfx.pfp_fw->data;
1340 		adev->gfx.pfp_fw_version =
1341 			le32_to_cpu(cp_hdr_v2_0->header.ucode_version);
1342 		adev->gfx.pfp_feature_version =
1343 			le32_to_cpu(cp_hdr_v2_0->ucode_feature_version);
1344 		ucode_fw = adev->gfx.pfp_fw;
1345 		fw_size = le32_to_cpu(cp_hdr_v2_0->ucode_size_bytes);
1346 		break;
1347 	case AMDGPU_UCODE_ID_CP_RS64_PFP_P0_STACK:
1348 	case AMDGPU_UCODE_ID_CP_RS64_PFP_P1_STACK:
1349 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1350 			adev->gfx.pfp_fw->data;
1351 		ucode_fw = adev->gfx.pfp_fw;
1352 		fw_size = le32_to_cpu(cp_hdr_v2_0->data_size_bytes);
1353 		break;
1354 	case AMDGPU_UCODE_ID_CP_ME:
1355 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1356 			adev->gfx.me_fw->data;
1357 		adev->gfx.me_fw_version =
1358 			le32_to_cpu(cp_hdr->header.ucode_version);
1359 		adev->gfx.me_feature_version =
1360 			le32_to_cpu(cp_hdr->ucode_feature_version);
1361 		ucode_fw = adev->gfx.me_fw;
1362 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes);
1363 		break;
1364 	case AMDGPU_UCODE_ID_CP_RS64_ME:
1365 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1366 			adev->gfx.me_fw->data;
1367 		adev->gfx.me_fw_version =
1368 			le32_to_cpu(cp_hdr_v2_0->header.ucode_version);
1369 		adev->gfx.me_feature_version =
1370 			le32_to_cpu(cp_hdr_v2_0->ucode_feature_version);
1371 		ucode_fw = adev->gfx.me_fw;
1372 		fw_size = le32_to_cpu(cp_hdr_v2_0->ucode_size_bytes);
1373 		break;
1374 	case AMDGPU_UCODE_ID_CP_RS64_ME_P0_STACK:
1375 	case AMDGPU_UCODE_ID_CP_RS64_ME_P1_STACK:
1376 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1377 			adev->gfx.me_fw->data;
1378 		ucode_fw = adev->gfx.me_fw;
1379 		fw_size = le32_to_cpu(cp_hdr_v2_0->data_size_bytes);
1380 		break;
1381 	case AMDGPU_UCODE_ID_CP_CE:
1382 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1383 			adev->gfx.ce_fw->data;
1384 		adev->gfx.ce_fw_version =
1385 			le32_to_cpu(cp_hdr->header.ucode_version);
1386 		adev->gfx.ce_feature_version =
1387 			le32_to_cpu(cp_hdr->ucode_feature_version);
1388 		ucode_fw = adev->gfx.ce_fw;
1389 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes);
1390 		break;
1391 	case AMDGPU_UCODE_ID_CP_MEC1:
1392 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1393 			adev->gfx.mec_fw->data;
1394 		adev->gfx.mec_fw_version =
1395 			le32_to_cpu(cp_hdr->header.ucode_version);
1396 		adev->gfx.mec_feature_version =
1397 			le32_to_cpu(cp_hdr->ucode_feature_version);
1398 		ucode_fw = adev->gfx.mec_fw;
1399 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes) -
1400 			  le32_to_cpu(cp_hdr->jt_size) * 4;
1401 		break;
1402 	case AMDGPU_UCODE_ID_CP_MEC1_JT:
1403 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1404 			adev->gfx.mec_fw->data;
1405 		ucode_fw = adev->gfx.mec_fw;
1406 		fw_size = le32_to_cpu(cp_hdr->jt_size) * 4;
1407 		break;
1408 	case AMDGPU_UCODE_ID_CP_MEC2:
1409 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1410 			adev->gfx.mec2_fw->data;
1411 		adev->gfx.mec2_fw_version =
1412 			le32_to_cpu(cp_hdr->header.ucode_version);
1413 		adev->gfx.mec2_feature_version =
1414 			le32_to_cpu(cp_hdr->ucode_feature_version);
1415 		ucode_fw = adev->gfx.mec2_fw;
1416 		fw_size = le32_to_cpu(cp_hdr->header.ucode_size_bytes) -
1417 			  le32_to_cpu(cp_hdr->jt_size) * 4;
1418 		break;
1419 	case AMDGPU_UCODE_ID_CP_MEC2_JT:
1420 		cp_hdr = (const struct gfx_firmware_header_v1_0 *)
1421 			adev->gfx.mec2_fw->data;
1422 		ucode_fw = adev->gfx.mec2_fw;
1423 		fw_size = le32_to_cpu(cp_hdr->jt_size) * 4;
1424 		break;
1425 	case AMDGPU_UCODE_ID_CP_RS64_MEC:
1426 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1427 			adev->gfx.mec_fw->data;
1428 		adev->gfx.mec_fw_version =
1429 			le32_to_cpu(cp_hdr_v2_0->header.ucode_version);
1430 		adev->gfx.mec_feature_version =
1431 			le32_to_cpu(cp_hdr_v2_0->ucode_feature_version);
1432 		ucode_fw = adev->gfx.mec_fw;
1433 		fw_size = le32_to_cpu(cp_hdr_v2_0->ucode_size_bytes);
1434 		break;
1435 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P0_STACK:
1436 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P1_STACK:
1437 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P2_STACK:
1438 	case AMDGPU_UCODE_ID_CP_RS64_MEC_P3_STACK:
1439 		cp_hdr_v2_0 = (const struct gfx_firmware_header_v2_0 *)
1440 			adev->gfx.mec_fw->data;
1441 		ucode_fw = adev->gfx.mec_fw;
1442 		fw_size = le32_to_cpu(cp_hdr_v2_0->data_size_bytes);
1443 		break;
1444 	default:
1445 		dev_err(adev->dev, "Invalid ucode id %u\n", ucode_id);
1446 		return;
1447 	}
1448 
1449 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
1450 		info = &adev->firmware.ucode[ucode_id];
1451 		info->ucode_id = ucode_id;
1452 		info->fw = ucode_fw;
1453 		adev->firmware.fw_size += ALIGN(fw_size, PAGE_SIZE);
1454 	}
1455 }
1456 
1457 bool amdgpu_gfx_is_master_xcc(struct amdgpu_device *adev, int xcc_id)
1458 {
1459 	return !(xcc_id % (adev->gfx.num_xcc_per_xcp ?
1460 			adev->gfx.num_xcc_per_xcp : 1));
1461 }
1462 
1463 static ssize_t amdgpu_gfx_get_current_compute_partition(struct device *dev,
1464 						struct device_attribute *addr,
1465 						char *buf)
1466 {
1467 	struct drm_device *ddev = dev_get_drvdata(dev);
1468 	struct amdgpu_device *adev = drm_to_adev(ddev);
1469 	int mode;
1470 
1471 	/* Only minimal precaution taken to reject requests while in reset.*/
1472 	if (amdgpu_in_reset(adev))
1473 		return -EPERM;
1474 
1475 	mode = amdgpu_xcp_query_partition_mode(adev->xcp_mgr,
1476 					       AMDGPU_XCP_FL_NONE);
1477 
1478 	return sysfs_emit(buf, "%s\n", amdgpu_gfx_compute_mode_desc(mode));
1479 }
1480 
1481 static ssize_t amdgpu_gfx_set_compute_partition(struct device *dev,
1482 						struct device_attribute *addr,
1483 						const char *buf, size_t count)
1484 {
1485 	struct drm_device *ddev = dev_get_drvdata(dev);
1486 	struct amdgpu_device *adev = drm_to_adev(ddev);
1487 	enum amdgpu_gfx_partition mode;
1488 	int ret = 0, num_xcc;
1489 
1490 	num_xcc = NUM_XCC(adev->gfx.xcc_mask);
1491 	if (num_xcc % 2 != 0)
1492 		return -EINVAL;
1493 
1494 	if (!strncasecmp("SPX", buf, strlen("SPX"))) {
1495 		mode = AMDGPU_SPX_PARTITION_MODE;
1496 	} else if (!strncasecmp("DPX", buf, strlen("DPX"))) {
1497 		/*
1498 		 * DPX mode needs AIDs to be in multiple of 2.
1499 		 * Each AID connects 2 XCCs.
1500 		 */
1501 		if (num_xcc%4)
1502 			return -EINVAL;
1503 		mode = AMDGPU_DPX_PARTITION_MODE;
1504 	} else if (!strncasecmp("TPX", buf, strlen("TPX"))) {
1505 		if (num_xcc != 6)
1506 			return -EINVAL;
1507 		mode = AMDGPU_TPX_PARTITION_MODE;
1508 	} else if (!strncasecmp("QPX", buf, strlen("QPX"))) {
1509 		if (num_xcc != 8)
1510 			return -EINVAL;
1511 		mode = AMDGPU_QPX_PARTITION_MODE;
1512 	} else if (!strncasecmp("CPX", buf, strlen("CPX"))) {
1513 		mode = AMDGPU_CPX_PARTITION_MODE;
1514 	} else {
1515 		return -EINVAL;
1516 	}
1517 
1518 	/* Don't allow a switch while under reset */
1519 	if (!down_read_trylock(&adev->reset_domain->sem))
1520 		return -EPERM;
1521 
1522 	ret = amdgpu_xcp_switch_partition_mode(adev->xcp_mgr, mode);
1523 
1524 	up_read(&adev->reset_domain->sem);
1525 
1526 	if (ret)
1527 		return ret;
1528 
1529 	return count;
1530 }
1531 
1532 static const char *xcp_desc[] = {
1533 	[AMDGPU_SPX_PARTITION_MODE] = "SPX",
1534 	[AMDGPU_DPX_PARTITION_MODE] = "DPX",
1535 	[AMDGPU_TPX_PARTITION_MODE] = "TPX",
1536 	[AMDGPU_QPX_PARTITION_MODE] = "QPX",
1537 	[AMDGPU_CPX_PARTITION_MODE] = "CPX",
1538 };
1539 
1540 static ssize_t amdgpu_gfx_get_available_compute_partition(struct device *dev,
1541 						struct device_attribute *addr,
1542 						char *buf)
1543 {
1544 	struct drm_device *ddev = dev_get_drvdata(dev);
1545 	struct amdgpu_device *adev = drm_to_adev(ddev);
1546 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
1547 	int size = 0, mode;
1548 	char *sep = "";
1549 
1550 	if (!xcp_mgr || !xcp_mgr->avail_xcp_modes)
1551 		return sysfs_emit(buf, "Not supported\n");
1552 
1553 	for_each_inst(mode, xcp_mgr->avail_xcp_modes) {
1554 		size += sysfs_emit_at(buf, size, "%s%s", sep, xcp_desc[mode]);
1555 		sep = ", ";
1556 	}
1557 
1558 	size += sysfs_emit_at(buf, size, "\n");
1559 
1560 	return size;
1561 }
1562 
1563 static int amdgpu_gfx_run_cleaner_shader_job(struct amdgpu_ring *ring)
1564 {
1565 	struct amdgpu_device *adev = ring->adev;
1566 	struct drm_gpu_scheduler *sched = &ring->sched;
1567 	struct drm_sched_entity entity;
1568 	static atomic_t counter;
1569 	struct dma_fence *f;
1570 	struct amdgpu_job *job;
1571 	struct amdgpu_ib *ib;
1572 	void *owner;
1573 	int i, r;
1574 
1575 	/* Initialize the scheduler entity */
1576 	r = drm_sched_entity_init(&entity, DRM_SCHED_PRIORITY_NORMAL,
1577 				  &sched, 1, NULL);
1578 	if (r) {
1579 		dev_err(adev->dev, "Failed setting up GFX kernel entity.\n");
1580 		goto err;
1581 	}
1582 
1583 	/*
1584 	 * Use some unique dummy value as the owner to make sure we execute
1585 	 * the cleaner shader on each submission. The value just need to change
1586 	 * for each submission and is otherwise meaningless.
1587 	 */
1588 	owner = (void *)(unsigned long)atomic_inc_return(&counter);
1589 
1590 	r = amdgpu_job_alloc_with_ib(ring->adev, &entity, owner,
1591 				     64, 0, &job,
1592 				     AMDGPU_KERNEL_JOB_ID_CLEANER_SHADER);
1593 	if (r)
1594 		goto err;
1595 
1596 	job->enforce_isolation = true;
1597 	/* always run the cleaner shader */
1598 	job->run_cleaner_shader = true;
1599 
1600 	ib = &job->ibs[0];
1601 	for (i = 0; i <= ring->funcs->align_mask; ++i)
1602 		ib->ptr[i] = ring->funcs->nop;
1603 	ib->length_dw = ring->funcs->align_mask + 1;
1604 
1605 	f = amdgpu_job_submit(job);
1606 
1607 	r = dma_fence_wait(f, false);
1608 	if (r)
1609 		goto err;
1610 
1611 	dma_fence_put(f);
1612 
1613 	/* Clean up the scheduler entity */
1614 	drm_sched_entity_destroy(&entity);
1615 	return 0;
1616 
1617 err:
1618 	return r;
1619 }
1620 
1621 static int amdgpu_gfx_run_cleaner_shader(struct amdgpu_device *adev, int xcp_id)
1622 {
1623 	int num_xcc = NUM_XCC(adev->gfx.xcc_mask);
1624 	struct amdgpu_ring *ring;
1625 	int num_xcc_to_clear;
1626 	int i, r, xcc_id;
1627 
1628 	if (adev->gfx.num_xcc_per_xcp)
1629 		num_xcc_to_clear = adev->gfx.num_xcc_per_xcp;
1630 	else
1631 		num_xcc_to_clear = 1;
1632 
1633 	for (xcc_id = 0; xcc_id < num_xcc; xcc_id++) {
1634 		for (i = 0; i < adev->gfx.num_compute_rings; i++) {
1635 			ring = &adev->gfx.compute_ring[i + xcc_id * adev->gfx.num_compute_rings];
1636 			if ((ring->xcp_id == xcp_id) && ring->sched.ready) {
1637 				r = amdgpu_gfx_run_cleaner_shader_job(ring);
1638 				if (r)
1639 					return r;
1640 				num_xcc_to_clear--;
1641 				break;
1642 			}
1643 		}
1644 	}
1645 
1646 	if (num_xcc_to_clear)
1647 		return -ENOENT;
1648 
1649 	return 0;
1650 }
1651 
1652 /**
1653  * amdgpu_gfx_set_run_cleaner_shader - Execute the AMDGPU GFX Cleaner Shader
1654  * @dev: The device structure
1655  * @attr: The device attribute structure
1656  * @buf: The buffer containing the input data
1657  * @count: The size of the input data
1658  *
1659  * Provides the sysfs interface to manually run a cleaner shader, which is
1660  * used to clear the GPU state between different tasks. Writing a value to the
1661  * 'run_cleaner_shader' sysfs file triggers the cleaner shader execution.
1662  * The value written corresponds to the partition index on multi-partition
1663  * devices. On single-partition devices, the value should be '0'.
1664  *
1665  * The cleaner shader clears the Local Data Store (LDS) and General Purpose
1666  * Registers (GPRs) to ensure data isolation between GPU workloads.
1667  *
1668  * Return: The number of bytes written to the sysfs file.
1669  */
1670 static ssize_t amdgpu_gfx_set_run_cleaner_shader(struct device *dev,
1671 						 struct device_attribute *attr,
1672 						 const char *buf,
1673 						 size_t count)
1674 {
1675 	struct drm_device *ddev = dev_get_drvdata(dev);
1676 	struct amdgpu_device *adev = drm_to_adev(ddev);
1677 	int ret;
1678 	long value;
1679 
1680 	if (amdgpu_in_reset(adev))
1681 		return -EPERM;
1682 	if (adev->in_suspend && !adev->in_runpm)
1683 		return -EPERM;
1684 
1685 	if (adev->gfx.disable_kq)
1686 		return -EPERM;
1687 
1688 	ret = kstrtol(buf, 0, &value);
1689 
1690 	if (ret)
1691 		return -EINVAL;
1692 
1693 	if (value < 0)
1694 		return -EINVAL;
1695 
1696 	if (adev->xcp_mgr) {
1697 		if (value >= adev->xcp_mgr->num_xcps)
1698 			return -EINVAL;
1699 	} else {
1700 		if (value > 1)
1701 			return -EINVAL;
1702 	}
1703 
1704 	ret = pm_runtime_get_sync(ddev->dev);
1705 	if (ret < 0) {
1706 		pm_runtime_put_autosuspend(ddev->dev);
1707 		return ret;
1708 	}
1709 
1710 	ret = amdgpu_gfx_run_cleaner_shader(adev, value);
1711 
1712 	pm_runtime_put_autosuspend(ddev->dev);
1713 
1714 	if (ret)
1715 		return ret;
1716 
1717 	return count;
1718 }
1719 
1720 /**
1721  * amdgpu_gfx_get_enforce_isolation - Query AMDGPU GFX Enforce Isolation Settings
1722  * @dev: The device structure
1723  * @attr: The device attribute structure
1724  * @buf: The buffer to store the output data
1725  *
1726  * Provides the sysfs read interface to get the current settings of the 'enforce_isolation'
1727  * feature for each GPU partition. Reading from the 'enforce_isolation'
1728  * sysfs file returns the isolation settings for all partitions, where '0'
1729  * indicates disabled, '1' indicates enabled, and '2' indicates enabled in legacy mode,
1730  * and '3' indicates enabled without cleaner shader.
1731  *
1732  * Return: The number of bytes read from the sysfs file.
1733  */
1734 static ssize_t amdgpu_gfx_get_enforce_isolation(struct device *dev,
1735 						struct device_attribute *attr,
1736 						char *buf)
1737 {
1738 	struct drm_device *ddev = dev_get_drvdata(dev);
1739 	struct amdgpu_device *adev = drm_to_adev(ddev);
1740 	int i;
1741 	ssize_t size = 0;
1742 
1743 	if (adev->xcp_mgr) {
1744 		for (i = 0; i < adev->xcp_mgr->num_xcps; i++) {
1745 			size += sysfs_emit_at(buf, size, "%u", adev->enforce_isolation[i]);
1746 			if (i < (adev->xcp_mgr->num_xcps - 1))
1747 				size += sysfs_emit_at(buf, size, " ");
1748 		}
1749 		buf[size++] = '\n';
1750 	} else {
1751 		size = sysfs_emit_at(buf, 0, "%u\n", adev->enforce_isolation[0]);
1752 	}
1753 
1754 	return size;
1755 }
1756 
1757 /**
1758  * amdgpu_gfx_set_enforce_isolation - Control AMDGPU GFX Enforce Isolation
1759  * @dev: The device structure
1760  * @attr: The device attribute structure
1761  * @buf: The buffer containing the input data
1762  * @count: The size of the input data
1763  *
1764  * This function allows control over the 'enforce_isolation' feature, which
1765  * serializes access to the graphics engine. Writing '0' to disable, '1' to
1766  * enable isolation with cleaner shader, '2' to enable legacy isolation without
1767  * cleaner shader, or '3' to enable process isolation without submitting the
1768  * cleaner shader to the 'enforce_isolation' sysfs file sets the isolation mode
1769  * for each partition. The input should specify the setting for all
1770  * partitions.
1771  *
1772  * Return: The number of bytes written to the sysfs file.
1773  */
1774 static ssize_t amdgpu_gfx_set_enforce_isolation(struct device *dev,
1775 						struct device_attribute *attr,
1776 						const char *buf, size_t count)
1777 {
1778 	struct drm_device *ddev = dev_get_drvdata(dev);
1779 	struct amdgpu_device *adev = drm_to_adev(ddev);
1780 	long partition_values[MAX_XCP] = {0};
1781 	int ret, i, num_partitions;
1782 	const char *input_buf = buf;
1783 
1784 	for (i = 0; i < (adev->xcp_mgr ? adev->xcp_mgr->num_xcps : 1); i++) {
1785 		ret = sscanf(input_buf, "%ld", &partition_values[i]);
1786 		if (ret <= 0)
1787 			break;
1788 
1789 		/* Move the pointer to the next value in the string */
1790 		input_buf = strchr(input_buf, ' ');
1791 		if (input_buf) {
1792 			input_buf++;
1793 		} else {
1794 			i++;
1795 			break;
1796 		}
1797 	}
1798 	num_partitions = i;
1799 
1800 	if (adev->xcp_mgr && num_partitions != adev->xcp_mgr->num_xcps)
1801 		return -EINVAL;
1802 
1803 	if (!adev->xcp_mgr && num_partitions != 1)
1804 		return -EINVAL;
1805 
1806 	for (i = 0; i < num_partitions; i++) {
1807 		if (partition_values[i] != 0 &&
1808 		    partition_values[i] != 1 &&
1809 		    partition_values[i] != 2 &&
1810 		    partition_values[i] != 3)
1811 			return -EINVAL;
1812 	}
1813 
1814 	mutex_lock(&adev->enforce_isolation_mutex);
1815 	for (i = 0; i < num_partitions; i++) {
1816 		switch (partition_values[i]) {
1817 		case 0:
1818 		default:
1819 			adev->enforce_isolation[i] = AMDGPU_ENFORCE_ISOLATION_DISABLE;
1820 			break;
1821 		case 1:
1822 			adev->enforce_isolation[i] =
1823 				AMDGPU_ENFORCE_ISOLATION_ENABLE;
1824 			break;
1825 		case 2:
1826 			adev->enforce_isolation[i] =
1827 				AMDGPU_ENFORCE_ISOLATION_ENABLE_LEGACY;
1828 			break;
1829 		case 3:
1830 			adev->enforce_isolation[i] =
1831 				AMDGPU_ENFORCE_ISOLATION_NO_CLEANER_SHADER;
1832 			break;
1833 		}
1834 	}
1835 	mutex_unlock(&adev->enforce_isolation_mutex);
1836 
1837 	amdgpu_mes_update_enforce_isolation(adev);
1838 
1839 	return count;
1840 }
1841 
1842 static ssize_t amdgpu_gfx_get_gfx_reset_mask(struct device *dev,
1843 						struct device_attribute *attr,
1844 						char *buf)
1845 {
1846 	struct drm_device *ddev = dev_get_drvdata(dev);
1847 	struct amdgpu_device *adev = drm_to_adev(ddev);
1848 
1849 	if (!adev)
1850 		return -ENODEV;
1851 
1852 	return amdgpu_show_reset_mask(buf, adev->gfx.gfx_supported_reset);
1853 }
1854 
1855 static ssize_t amdgpu_gfx_get_compute_reset_mask(struct device *dev,
1856 						struct device_attribute *attr,
1857 						char *buf)
1858 {
1859 	struct drm_device *ddev = dev_get_drvdata(dev);
1860 	struct amdgpu_device *adev = drm_to_adev(ddev);
1861 
1862 	if (!adev)
1863 		return -ENODEV;
1864 
1865 	return amdgpu_show_reset_mask(buf, adev->gfx.compute_supported_reset);
1866 }
1867 
1868 static DEVICE_ATTR(run_cleaner_shader, 0200,
1869 		   NULL, amdgpu_gfx_set_run_cleaner_shader);
1870 
1871 static DEVICE_ATTR(enforce_isolation, 0644,
1872 		   amdgpu_gfx_get_enforce_isolation,
1873 		   amdgpu_gfx_set_enforce_isolation);
1874 
1875 static DEVICE_ATTR(current_compute_partition, 0644,
1876 		   amdgpu_gfx_get_current_compute_partition,
1877 		   amdgpu_gfx_set_compute_partition);
1878 
1879 static DEVICE_ATTR(available_compute_partition, 0444,
1880 		   amdgpu_gfx_get_available_compute_partition, NULL);
1881 static DEVICE_ATTR(gfx_reset_mask, 0444,
1882 		   amdgpu_gfx_get_gfx_reset_mask, NULL);
1883 
1884 static DEVICE_ATTR(compute_reset_mask, 0444,
1885 		   amdgpu_gfx_get_compute_reset_mask, NULL);
1886 
1887 static int amdgpu_gfx_sysfs_xcp_init(struct amdgpu_device *adev)
1888 {
1889 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
1890 	bool xcp_switch_supported;
1891 	int r;
1892 
1893 	if (!xcp_mgr)
1894 		return 0;
1895 
1896 	xcp_switch_supported =
1897 		(xcp_mgr->funcs && xcp_mgr->funcs->switch_partition_mode);
1898 
1899 	if (!xcp_switch_supported)
1900 		dev_attr_current_compute_partition.attr.mode &=
1901 			~(S_IWUSR | S_IWGRP | S_IWOTH);
1902 
1903 	r = device_create_file(adev->dev, &dev_attr_current_compute_partition);
1904 	if (r)
1905 		return r;
1906 
1907 	if (xcp_switch_supported)
1908 		r = device_create_file(adev->dev,
1909 				       &dev_attr_available_compute_partition);
1910 
1911 	return r;
1912 }
1913 
1914 static void amdgpu_gfx_sysfs_xcp_fini(struct amdgpu_device *adev)
1915 {
1916 	struct amdgpu_xcp_mgr *xcp_mgr = adev->xcp_mgr;
1917 	bool xcp_switch_supported;
1918 
1919 	if (!xcp_mgr)
1920 		return;
1921 
1922 	xcp_switch_supported =
1923 		(xcp_mgr->funcs && xcp_mgr->funcs->switch_partition_mode);
1924 	device_remove_file(adev->dev, &dev_attr_current_compute_partition);
1925 
1926 	if (xcp_switch_supported)
1927 		device_remove_file(adev->dev,
1928 				   &dev_attr_available_compute_partition);
1929 }
1930 
1931 static int amdgpu_gfx_sysfs_isolation_shader_init(struct amdgpu_device *adev)
1932 {
1933 	int r;
1934 
1935 	r = device_create_file(adev->dev, &dev_attr_enforce_isolation);
1936 	if (r)
1937 		return r;
1938 	if (adev->gfx.enable_cleaner_shader)
1939 		r = device_create_file(adev->dev, &dev_attr_run_cleaner_shader);
1940 
1941 	return r;
1942 }
1943 
1944 static void amdgpu_gfx_sysfs_isolation_shader_fini(struct amdgpu_device *adev)
1945 {
1946 	device_remove_file(adev->dev, &dev_attr_enforce_isolation);
1947 	if (adev->gfx.enable_cleaner_shader)
1948 		device_remove_file(adev->dev, &dev_attr_run_cleaner_shader);
1949 }
1950 
1951 static int amdgpu_gfx_sysfs_reset_mask_init(struct amdgpu_device *adev)
1952 {
1953 	int r = 0;
1954 
1955 	if (!amdgpu_gpu_recovery)
1956 		return r;
1957 
1958 	if (adev->gfx.num_gfx_rings) {
1959 		r = device_create_file(adev->dev, &dev_attr_gfx_reset_mask);
1960 		if (r)
1961 			return r;
1962 	}
1963 
1964 	if (adev->gfx.num_compute_rings) {
1965 		r = device_create_file(adev->dev, &dev_attr_compute_reset_mask);
1966 		if (r)
1967 			return r;
1968 	}
1969 
1970 	return r;
1971 }
1972 
1973 static void amdgpu_gfx_sysfs_reset_mask_fini(struct amdgpu_device *adev)
1974 {
1975 	if (!amdgpu_gpu_recovery)
1976 		return;
1977 
1978 	if (adev->gfx.num_gfx_rings)
1979 		device_remove_file(adev->dev, &dev_attr_gfx_reset_mask);
1980 
1981 	if (adev->gfx.num_compute_rings)
1982 		device_remove_file(adev->dev, &dev_attr_compute_reset_mask);
1983 }
1984 
1985 int amdgpu_gfx_sysfs_init(struct amdgpu_device *adev)
1986 {
1987 	int r;
1988 
1989 	r = amdgpu_gfx_sysfs_xcp_init(adev);
1990 	if (r) {
1991 		dev_err(adev->dev, "failed to create xcp sysfs files");
1992 		return r;
1993 	}
1994 
1995 	r = amdgpu_gfx_sysfs_isolation_shader_init(adev);
1996 	if (r)
1997 		dev_err(adev->dev, "failed to create isolation sysfs files");
1998 
1999 	r = amdgpu_gfx_sysfs_reset_mask_init(adev);
2000 	if (r)
2001 		dev_err(adev->dev, "failed to create reset mask sysfs files");
2002 
2003 	return r;
2004 }
2005 
2006 void amdgpu_gfx_sysfs_fini(struct amdgpu_device *adev)
2007 {
2008 	if (adev->dev->kobj.sd) {
2009 		amdgpu_gfx_sysfs_xcp_fini(adev);
2010 		amdgpu_gfx_sysfs_isolation_shader_fini(adev);
2011 		amdgpu_gfx_sysfs_reset_mask_fini(adev);
2012 	}
2013 }
2014 
2015 int amdgpu_gfx_cleaner_shader_sw_init(struct amdgpu_device *adev,
2016 				      unsigned int cleaner_shader_size)
2017 {
2018 	if (!adev->gfx.enable_cleaner_shader)
2019 		return -EOPNOTSUPP;
2020 
2021 	return amdgpu_bo_create_kernel(adev, cleaner_shader_size, PAGE_SIZE,
2022 				       AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2023 				       &adev->gfx.cleaner_shader_obj,
2024 				       &adev->gfx.cleaner_shader_gpu_addr,
2025 				       (void **)&adev->gfx.cleaner_shader_cpu_ptr);
2026 }
2027 
2028 void amdgpu_gfx_cleaner_shader_sw_fini(struct amdgpu_device *adev)
2029 {
2030 	if (!adev->gfx.enable_cleaner_shader)
2031 		return;
2032 
2033 	amdgpu_bo_free_kernel(&adev->gfx.cleaner_shader_obj,
2034 			      &adev->gfx.cleaner_shader_gpu_addr,
2035 			      (void **)&adev->gfx.cleaner_shader_cpu_ptr);
2036 }
2037 
2038 void amdgpu_gfx_cleaner_shader_init(struct amdgpu_device *adev,
2039 				    unsigned int cleaner_shader_size,
2040 				    const void *cleaner_shader_ptr)
2041 {
2042 	if (!adev->gfx.enable_cleaner_shader)
2043 		return;
2044 
2045 	if (adev->gfx.cleaner_shader_cpu_ptr && cleaner_shader_ptr)
2046 		memcpy_toio(adev->gfx.cleaner_shader_cpu_ptr, cleaner_shader_ptr,
2047 			    cleaner_shader_size);
2048 }
2049 
2050 /**
2051  * amdgpu_gfx_kfd_sch_ctrl - Control the KFD scheduler from the KGD (Graphics Driver)
2052  * @adev: amdgpu_device pointer
2053  * @idx: Index of the scheduler to control
2054  * @enable: Whether to enable or disable the KFD scheduler
2055  *
2056  * This function is used to control the KFD (Kernel Fusion Driver) scheduler
2057  * from the KGD. It is part of the cleaner shader feature. This function plays
2058  * a key role in enforcing process isolation on the GPU.
2059  *
2060  * The function uses a reference count mechanism (kfd_sch_req_count) to keep
2061  * track of the number of requests to enable the KFD scheduler. When a request
2062  * to enable the KFD scheduler is made, the reference count is decremented.
2063  * When the reference count reaches zero, a delayed work is scheduled to
2064  * enforce isolation after a delay of GFX_SLICE_PERIOD.
2065  *
2066  * When a request to disable the KFD scheduler is made, the function first
2067  * checks if the reference count is zero. If it is, it cancels the delayed work
2068  * for enforcing isolation and checks if the KFD scheduler is active. If the
2069  * KFD scheduler is active, it sends a request to stop the KFD scheduler and
2070  * sets the KFD scheduler state to inactive. Then, it increments the reference
2071  * count.
2072  *
2073  * The function is synchronized using the kfd_sch_mutex to ensure that the KFD
2074  * scheduler state and reference count are updated atomically.
2075  *
2076  * Note: If the reference count is already zero when a request to enable the
2077  * KFD scheduler is made, it means there's an imbalance bug somewhere. The
2078  * function triggers a warning in this case.
2079  */
2080 static void amdgpu_gfx_kfd_sch_ctrl(struct amdgpu_device *adev, u32 idx,
2081 				    bool enable)
2082 {
2083 	mutex_lock(&adev->gfx.userq_sch_mutex);
2084 
2085 	if (enable) {
2086 		/* If the count is already 0, it means there's an imbalance bug somewhere.
2087 		 * Note that the bug may be in a different caller than the one which triggers the
2088 		 * WARN_ON_ONCE.
2089 		 */
2090 		if (WARN_ON_ONCE(adev->gfx.userq_sch_req_count[idx] == 0)) {
2091 			dev_err(adev->dev, "Attempted to enable KFD scheduler when reference count is already zero\n");
2092 			goto unlock;
2093 		}
2094 
2095 		adev->gfx.userq_sch_req_count[idx]--;
2096 
2097 		if (adev->gfx.userq_sch_req_count[idx] == 0 &&
2098 		    adev->gfx.userq_sch_inactive[idx]) {
2099 			schedule_delayed_work(&adev->gfx.enforce_isolation[idx].work,
2100 					      msecs_to_jiffies(adev->gfx.enforce_isolation_time[idx]));
2101 		}
2102 	} else {
2103 		if (adev->gfx.userq_sch_req_count[idx] == 0) {
2104 			cancel_delayed_work_sync(&adev->gfx.enforce_isolation[idx].work);
2105 			if (!adev->gfx.userq_sch_inactive[idx]) {
2106 				amdgpu_userq_stop_sched_for_enforce_isolation(adev, idx);
2107 				if (adev->kfd.init_complete)
2108 					amdgpu_amdkfd_stop_sched(adev, idx);
2109 				adev->gfx.userq_sch_inactive[idx] = true;
2110 			}
2111 		}
2112 
2113 		adev->gfx.userq_sch_req_count[idx]++;
2114 	}
2115 
2116 unlock:
2117 	mutex_unlock(&adev->gfx.userq_sch_mutex);
2118 }
2119 
2120 /**
2121  * amdgpu_gfx_enforce_isolation_handler - work handler for enforcing shader isolation
2122  *
2123  * @work: work_struct.
2124  *
2125  * This function is the work handler for enforcing shader isolation on AMD GPUs.
2126  * It counts the number of emitted fences for each GFX and compute ring. If there
2127  * are any fences, it schedules the `enforce_isolation_work` to be run after a
2128  * delay of `GFX_SLICE_PERIOD`. If there are no fences, it signals the Kernel Fusion
2129  * Driver (KFD) to resume the runqueue. The function is synchronized using the
2130  * `enforce_isolation_mutex`.
2131  */
2132 void amdgpu_gfx_enforce_isolation_handler(struct work_struct *work)
2133 {
2134 	struct amdgpu_isolation_work *isolation_work =
2135 		container_of(work, struct amdgpu_isolation_work, work.work);
2136 	struct amdgpu_device *adev = isolation_work->adev;
2137 	u32 i, idx, fences = 0;
2138 
2139 	if (isolation_work->xcp_id == AMDGPU_XCP_NO_PARTITION)
2140 		idx = 0;
2141 	else
2142 		idx = isolation_work->xcp_id;
2143 
2144 	if (idx >= MAX_XCP)
2145 		return;
2146 
2147 	mutex_lock(&adev->enforce_isolation_mutex);
2148 	for (i = 0; i < AMDGPU_MAX_GFX_RINGS; ++i) {
2149 		if (isolation_work->xcp_id == adev->gfx.gfx_ring[i].xcp_id)
2150 			fences += amdgpu_fence_count_emitted(&adev->gfx.gfx_ring[i]);
2151 	}
2152 	for (i = 0; i < (AMDGPU_MAX_COMPUTE_RINGS * AMDGPU_MAX_GC_INSTANCES); ++i) {
2153 		if (isolation_work->xcp_id == adev->gfx.compute_ring[i].xcp_id)
2154 			fences += amdgpu_fence_count_emitted(&adev->gfx.compute_ring[i]);
2155 	}
2156 	if (fences) {
2157 		/* we've already had our timeslice, so let's wrap this up */
2158 		schedule_delayed_work(&adev->gfx.enforce_isolation[idx].work,
2159 				      msecs_to_jiffies(1));
2160 	} else {
2161 		/* Tell KFD to resume the runqueue */
2162 		WARN_ON_ONCE(!adev->gfx.userq_sch_inactive[idx]);
2163 		WARN_ON_ONCE(adev->gfx.userq_sch_req_count[idx]);
2164 
2165 		amdgpu_userq_start_sched_for_enforce_isolation(adev, idx);
2166 		if (adev->kfd.init_complete)
2167 			amdgpu_amdkfd_start_sched(adev, idx);
2168 		adev->gfx.userq_sch_inactive[idx] = false;
2169 	}
2170 	mutex_unlock(&adev->enforce_isolation_mutex);
2171 }
2172 
2173 /**
2174  * amdgpu_gfx_enforce_isolation_wait_for_kfd - Manage KFD wait period for process isolation
2175  * @adev: amdgpu_device pointer
2176  * @idx: Index of the GPU partition
2177  *
2178  * When kernel submissions come in, the jobs are given a time slice and once
2179  * that time slice is up, if there are KFD user queues active, kernel
2180  * submissions are blocked until KFD has had its time slice. Once the KFD time
2181  * slice is up, KFD user queues are preempted and kernel submissions are
2182  * unblocked and allowed to run again.
2183  */
2184 static void
2185 amdgpu_gfx_enforce_isolation_wait_for_kfd(struct amdgpu_device *adev,
2186 					  u32 idx)
2187 {
2188 	unsigned long cjiffies;
2189 	bool wait = false;
2190 
2191 	mutex_lock(&adev->enforce_isolation_mutex);
2192 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2193 		/* set the initial values if nothing is set */
2194 		if (!adev->gfx.enforce_isolation_jiffies[idx]) {
2195 			adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2196 			adev->gfx.enforce_isolation_time[idx] =	GFX_SLICE_PERIOD_MS;
2197 		}
2198 		/* Make sure KFD gets a chance to run */
2199 		if (amdgpu_amdkfd_compute_active(adev, idx)) {
2200 			cjiffies = jiffies;
2201 			if (time_after(cjiffies, adev->gfx.enforce_isolation_jiffies[idx])) {
2202 				cjiffies -= adev->gfx.enforce_isolation_jiffies[idx];
2203 				if ((jiffies_to_msecs(cjiffies) >= GFX_SLICE_PERIOD_MS)) {
2204 					/* if our time is up, let KGD work drain before scheduling more */
2205 					wait = true;
2206 					/* reset the timer period */
2207 					adev->gfx.enforce_isolation_time[idx] =	GFX_SLICE_PERIOD_MS;
2208 				} else {
2209 					/* set the timer period to what's left in our time slice */
2210 					adev->gfx.enforce_isolation_time[idx] =
2211 						GFX_SLICE_PERIOD_MS - jiffies_to_msecs(cjiffies);
2212 				}
2213 			} else {
2214 				/* if jiffies wrap around we will just wait a little longer */
2215 				adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2216 			}
2217 		} else {
2218 			/* if there is no KFD work, then set the full slice period */
2219 			adev->gfx.enforce_isolation_jiffies[idx] = jiffies;
2220 			adev->gfx.enforce_isolation_time[idx] = GFX_SLICE_PERIOD_MS;
2221 		}
2222 	}
2223 	mutex_unlock(&adev->enforce_isolation_mutex);
2224 
2225 	if (wait)
2226 		msleep(GFX_SLICE_PERIOD_MS);
2227 }
2228 
2229 /**
2230  * amdgpu_gfx_enforce_isolation_ring_begin_use - Begin use of a ring with enforced isolation
2231  * @ring: Pointer to the amdgpu_ring structure
2232  *
2233  * Ring begin_use helper implementation for gfx which serializes access to the
2234  * gfx IP between kernel submission IOCTLs and KFD user queues when isolation
2235  * enforcement is enabled. The kernel submission IOCTLs and KFD user queues
2236  * each get a time slice when both are active.
2237  */
2238 void amdgpu_gfx_enforce_isolation_ring_begin_use(struct amdgpu_ring *ring)
2239 {
2240 	struct amdgpu_device *adev = ring->adev;
2241 	u32 idx;
2242 	bool sched_work = false;
2243 
2244 	if (!adev->gfx.enable_cleaner_shader)
2245 		return;
2246 
2247 	if (ring->xcp_id == AMDGPU_XCP_NO_PARTITION)
2248 		idx = 0;
2249 	else
2250 		idx = ring->xcp_id;
2251 
2252 	if (idx >= MAX_XCP)
2253 		return;
2254 
2255 	/* Don't submit more work until KFD has had some time */
2256 	amdgpu_gfx_enforce_isolation_wait_for_kfd(adev, idx);
2257 
2258 	mutex_lock(&adev->enforce_isolation_mutex);
2259 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2260 		if (adev->kfd.init_complete)
2261 			sched_work = true;
2262 	}
2263 	mutex_unlock(&adev->enforce_isolation_mutex);
2264 
2265 	if (sched_work)
2266 		amdgpu_gfx_kfd_sch_ctrl(adev, idx, false);
2267 }
2268 
2269 /**
2270  * amdgpu_gfx_enforce_isolation_ring_end_use - End use of a ring with enforced isolation
2271  * @ring: Pointer to the amdgpu_ring structure
2272  *
2273  * Ring end_use helper implementation for gfx which serializes access to the
2274  * gfx IP between kernel submission IOCTLs and KFD user queues when isolation
2275  * enforcement is enabled. The kernel submission IOCTLs and KFD user queues
2276  * each get a time slice when both are active.
2277  */
2278 void amdgpu_gfx_enforce_isolation_ring_end_use(struct amdgpu_ring *ring)
2279 {
2280 	struct amdgpu_device *adev = ring->adev;
2281 	u32 idx;
2282 	bool sched_work = false;
2283 
2284 	if (!adev->gfx.enable_cleaner_shader)
2285 		return;
2286 
2287 	if (ring->xcp_id == AMDGPU_XCP_NO_PARTITION)
2288 		idx = 0;
2289 	else
2290 		idx = ring->xcp_id;
2291 
2292 	if (idx >= MAX_XCP)
2293 		return;
2294 
2295 	mutex_lock(&adev->enforce_isolation_mutex);
2296 	if (adev->enforce_isolation[idx] == AMDGPU_ENFORCE_ISOLATION_ENABLE) {
2297 		if (adev->kfd.init_complete)
2298 			sched_work = true;
2299 	}
2300 	mutex_unlock(&adev->enforce_isolation_mutex);
2301 
2302 	if (sched_work)
2303 		amdgpu_gfx_kfd_sch_ctrl(adev, idx, true);
2304 }
2305 
2306 void amdgpu_gfx_profile_idle_work_handler(struct work_struct *work)
2307 {
2308 	struct amdgpu_device *adev =
2309 		container_of(work, struct amdgpu_device, gfx.idle_work.work);
2310 	enum PP_SMC_POWER_PROFILE profile;
2311 	u32 i, fences = 0;
2312 	int r;
2313 
2314 	if (adev->gfx.num_gfx_rings)
2315 		profile = PP_SMC_POWER_PROFILE_FULLSCREEN3D;
2316 	else
2317 		profile = PP_SMC_POWER_PROFILE_COMPUTE;
2318 
2319 	for (i = 0; i < AMDGPU_MAX_GFX_RINGS; ++i)
2320 		fences += amdgpu_fence_count_emitted(&adev->gfx.gfx_ring[i]);
2321 	for (i = 0; i < (AMDGPU_MAX_COMPUTE_RINGS * AMDGPU_MAX_GC_INSTANCES); ++i)
2322 		fences += amdgpu_fence_count_emitted(&adev->gfx.compute_ring[i]);
2323 	if (!fences && !atomic_read(&adev->gfx.total_submission_cnt)) {
2324 		mutex_lock(&adev->gfx.workload_profile_mutex);
2325 		if (adev->gfx.workload_profile_active) {
2326 			r = amdgpu_dpm_switch_power_profile(adev, profile, false);
2327 			if (r)
2328 				dev_warn(adev->dev, "(%d) failed to disable %s power profile mode\n", r,
2329 					 profile == PP_SMC_POWER_PROFILE_FULLSCREEN3D ?
2330 					 "fullscreen 3D" : "compute");
2331 			adev->gfx.workload_profile_active = false;
2332 		}
2333 		mutex_unlock(&adev->gfx.workload_profile_mutex);
2334 	} else {
2335 		schedule_delayed_work(&adev->gfx.idle_work, GFX_PROFILE_IDLE_TIMEOUT);
2336 	}
2337 }
2338 
2339 void amdgpu_gfx_profile_ring_begin_use(struct amdgpu_ring *ring)
2340 {
2341 	struct amdgpu_device *adev = ring->adev;
2342 	enum PP_SMC_POWER_PROFILE profile;
2343 	int r;
2344 
2345 	if (amdgpu_dpm_is_overdrive_enabled(adev))
2346 		return;
2347 
2348 	if (adev->gfx.num_gfx_rings)
2349 		profile = PP_SMC_POWER_PROFILE_FULLSCREEN3D;
2350 	else
2351 		profile = PP_SMC_POWER_PROFILE_COMPUTE;
2352 
2353 	atomic_inc(&adev->gfx.total_submission_cnt);
2354 
2355 	cancel_delayed_work_sync(&adev->gfx.idle_work);
2356 
2357 	/* We can safely return early here because we've cancelled the
2358 	 * the delayed work so there is no one else to set it to false
2359 	 * and we don't care if someone else sets it to true.
2360 	 */
2361 	if (adev->gfx.workload_profile_active)
2362 		return;
2363 
2364 	mutex_lock(&adev->gfx.workload_profile_mutex);
2365 	if (!adev->gfx.workload_profile_active) {
2366 		r = amdgpu_dpm_switch_power_profile(adev, profile, true);
2367 		if (r)
2368 			dev_warn(adev->dev, "(%d) failed to disable %s power profile mode\n", r,
2369 				 profile == PP_SMC_POWER_PROFILE_FULLSCREEN3D ?
2370 				 "fullscreen 3D" : "compute");
2371 		adev->gfx.workload_profile_active = true;
2372 	}
2373 	mutex_unlock(&adev->gfx.workload_profile_mutex);
2374 }
2375 
2376 void amdgpu_gfx_profile_ring_end_use(struct amdgpu_ring *ring)
2377 {
2378 	struct amdgpu_device *adev = ring->adev;
2379 
2380 	if (amdgpu_dpm_is_overdrive_enabled(adev))
2381 		return;
2382 
2383 	atomic_dec(&ring->adev->gfx.total_submission_cnt);
2384 
2385 	schedule_delayed_work(&ring->adev->gfx.idle_work, GFX_PROFILE_IDLE_TIMEOUT);
2386 }
2387 
2388 /**
2389  * amdgpu_gfx_csb_preamble_start - Set CSB preamble start
2390  *
2391  * @buffer: This is an output variable that gets the PACKET3 preamble setup.
2392  *
2393  * Return:
2394  * return the latest index.
2395  */
2396 u32 amdgpu_gfx_csb_preamble_start(u32 *buffer)
2397 {
2398 	u32 count = 0;
2399 
2400 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
2401 	buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_BEGIN_CLEAR_STATE);
2402 
2403 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CONTEXT_CONTROL, 1));
2404 	buffer[count++] = cpu_to_le32(0x80000000);
2405 	buffer[count++] = cpu_to_le32(0x80000000);
2406 
2407 	return count;
2408 }
2409 
2410 /**
2411  * amdgpu_gfx_csb_data_parser - Parser CS data
2412  *
2413  * @adev: amdgpu_device pointer used to get the CS data and other gfx info.
2414  * @buffer: This is an output variable that gets the PACKET3 preamble end.
2415  * @count: Index to start set the preemble end.
2416  *
2417  * Return:
2418  * return the latest index.
2419  */
2420 u32 amdgpu_gfx_csb_data_parser(struct amdgpu_device *adev, u32 *buffer, u32 count)
2421 {
2422 	const struct cs_section_def *sect = NULL;
2423 	const struct cs_extent_def *ext = NULL;
2424 	u32 i;
2425 
2426 	for (sect = adev->gfx.rlc.cs_data; sect->section != NULL; ++sect) {
2427 		for (ext = sect->section; ext->extent != NULL; ++ext) {
2428 			if (sect->id == SECT_CONTEXT) {
2429 				buffer[count++] = cpu_to_le32(PACKET3(PACKET3_SET_CONTEXT_REG, ext->reg_count));
2430 				buffer[count++] = cpu_to_le32(ext->reg_index - PACKET3_SET_CONTEXT_REG_START);
2431 
2432 				for (i = 0; i < ext->reg_count; i++)
2433 					buffer[count++] = cpu_to_le32(ext->extent[i]);
2434 			}
2435 		}
2436 	}
2437 
2438 	return count;
2439 }
2440 
2441 /**
2442  * amdgpu_gfx_csb_preamble_end - Set CSB preamble end
2443  *
2444  * @buffer: This is an output variable that gets the PACKET3 preamble end.
2445  * @count: Index to start set the preemble end.
2446  */
2447 void amdgpu_gfx_csb_preamble_end(u32 *buffer, u32 count)
2448 {
2449 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_PREAMBLE_CNTL, 0));
2450 	buffer[count++] = cpu_to_le32(PACKET3_PREAMBLE_END_CLEAR_STATE);
2451 
2452 	buffer[count++] = cpu_to_le32(PACKET3(PACKET3_CLEAR_STATE, 0));
2453 	buffer[count++] = cpu_to_le32(0);
2454 }
2455 
2456 /*
2457  * debugfs for to enable/disable gfx job submission to specific core.
2458  */
2459 #if defined(CONFIG_DEBUG_FS)
2460 static int amdgpu_debugfs_gfx_sched_mask_set(void *data, u64 val)
2461 {
2462 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2463 	u32 i;
2464 	u64 mask = 0;
2465 	struct amdgpu_ring *ring;
2466 
2467 	if (!adev)
2468 		return -ENODEV;
2469 
2470 	mask = (1ULL << adev->gfx.num_gfx_rings) - 1;
2471 	if ((val & mask) == 0)
2472 		return -EINVAL;
2473 
2474 	for (i = 0; i < adev->gfx.num_gfx_rings; ++i) {
2475 		ring = &adev->gfx.gfx_ring[i];
2476 		if (val & (1 << i))
2477 			ring->sched.ready = true;
2478 		else
2479 			ring->sched.ready = false;
2480 	}
2481 	/* publish sched.ready flag update effective immediately across smp */
2482 	smp_rmb();
2483 	return 0;
2484 }
2485 
2486 static int amdgpu_debugfs_gfx_sched_mask_get(void *data, u64 *val)
2487 {
2488 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2489 	u32 i;
2490 	u64 mask = 0;
2491 	struct amdgpu_ring *ring;
2492 
2493 	if (!adev)
2494 		return -ENODEV;
2495 	for (i = 0; i < adev->gfx.num_gfx_rings; ++i) {
2496 		ring = &adev->gfx.gfx_ring[i];
2497 		if (ring->sched.ready)
2498 			mask |= 1ULL << i;
2499 	}
2500 
2501 	*val = mask;
2502 	return 0;
2503 }
2504 
2505 DEFINE_DEBUGFS_ATTRIBUTE(amdgpu_debugfs_gfx_sched_mask_fops,
2506 			 amdgpu_debugfs_gfx_sched_mask_get,
2507 			 amdgpu_debugfs_gfx_sched_mask_set, "%llx\n");
2508 
2509 #endif
2510 
2511 void amdgpu_debugfs_gfx_sched_mask_init(struct amdgpu_device *adev)
2512 {
2513 #if defined(CONFIG_DEBUG_FS)
2514 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2515 	struct dentry *root = minor->debugfs_root;
2516 	char name[32];
2517 
2518 	if (!(adev->gfx.num_gfx_rings > 1))
2519 		return;
2520 	sprintf(name, "amdgpu_gfx_sched_mask");
2521 	debugfs_create_file(name, 0600, root, adev,
2522 			    &amdgpu_debugfs_gfx_sched_mask_fops);
2523 #endif
2524 }
2525 
2526 /*
2527  * debugfs for to enable/disable compute job submission to specific core.
2528  */
2529 #if defined(CONFIG_DEBUG_FS)
2530 static int amdgpu_debugfs_compute_sched_mask_set(void *data, u64 val)
2531 {
2532 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2533 	u32 i;
2534 	u64 mask = 0;
2535 	struct amdgpu_ring *ring;
2536 
2537 	if (!adev)
2538 		return -ENODEV;
2539 
2540 	mask = (1ULL << adev->gfx.num_compute_rings) - 1;
2541 	if ((val & mask) == 0)
2542 		return -EINVAL;
2543 
2544 	for (i = 0; i < adev->gfx.num_compute_rings; ++i) {
2545 		ring = &adev->gfx.compute_ring[i];
2546 		if (val & (1 << i))
2547 			ring->sched.ready = true;
2548 		else
2549 			ring->sched.ready = false;
2550 	}
2551 
2552 	/* publish sched.ready flag update effective immediately across smp */
2553 	smp_rmb();
2554 	return 0;
2555 }
2556 
2557 static int amdgpu_debugfs_compute_sched_mask_get(void *data, u64 *val)
2558 {
2559 	struct amdgpu_device *adev = (struct amdgpu_device *)data;
2560 	u32 i;
2561 	u64 mask = 0;
2562 	struct amdgpu_ring *ring;
2563 
2564 	if (!adev)
2565 		return -ENODEV;
2566 	for (i = 0; i < adev->gfx.num_compute_rings; ++i) {
2567 		ring = &adev->gfx.compute_ring[i];
2568 		if (ring->sched.ready)
2569 			mask |= 1ULL << i;
2570 	}
2571 
2572 	*val = mask;
2573 	return 0;
2574 }
2575 
2576 DEFINE_DEBUGFS_ATTRIBUTE(amdgpu_debugfs_compute_sched_mask_fops,
2577 			 amdgpu_debugfs_compute_sched_mask_get,
2578 			 amdgpu_debugfs_compute_sched_mask_set, "%llx\n");
2579 
2580 #endif
2581 
2582 void amdgpu_debugfs_compute_sched_mask_init(struct amdgpu_device *adev)
2583 {
2584 #if defined(CONFIG_DEBUG_FS)
2585 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2586 	struct dentry *root = minor->debugfs_root;
2587 	char name[32];
2588 
2589 	if (!(adev->gfx.num_compute_rings > 1))
2590 		return;
2591 	sprintf(name, "amdgpu_compute_sched_mask");
2592 	debugfs_create_file(name, 0600, root, adev,
2593 			    &amdgpu_debugfs_compute_sched_mask_fops);
2594 #endif
2595 }
2596 
2597