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